Lowest Bit Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KB Total submit users: 415, Accepted users: 389 Problem 10038 : No special judgement Problem description Given an positive integer A (1 <= A <= 109), output the lowest bit of A. For example, given A = 26, we can write A in binary form as 11010, so the lowest bit of A is 10, so the output should be 2. Another example goes like this: given A = 88, we can write A in binary form as 1011000, so the lowest bit of A is 1000, so the output should be 8.
Input Each line of input contains only an integer A (1 <= A <= 109). A line containing "0" indicates the end of input, and this line is not a part of the input data.
Output For each A in the input, output a line containing only its lowest bit.
Sample Input 26 8 0
Sample Output 2 8
Problem Source HNU 1'st Contest
郁闷,又是三次才AC!
// 315.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<iostream> #include<math.h> usingnamespace std; //#define MAX_SIZE 30; int Bin_Arr[30]=...{0,}; //全局二进制数组 int N=0; //N记录二进制位数 void DecToBin(int Dec) ...{ if(Dec==1) Bin_Arr[N]=1; else ...{ Bin_Arr[N]=Dec%2; Dec=Dec/2; N++; DecToBin(Dec); } } int LowBit() ...{ for(int x=0;x<N+1;x++) ...{ if(Bin_Arr[x]==0) 1; else return pow(2,x); } return0; } int main() ...{ int Num=0,temp=0; int i=0; while(1) ...{ cin>>Num; if(Num==0) break; N=0; for(int z=0;z<30;z++) Bin_Arr[z]=0; DecToBin(Num); // for(int p=0;p<30;p++) // cout<<Bin_Arr[p]; temp=LowBit(); cout<<temp<<endl; i++; } return0; }
同样附上“马牛不是人”的解法(每次他的代码都比我精简很多,诶~):
#include <stdio.h> #include <math.h>
int getbits(int); main() { int n; scanf("%d",&n); while(n!=0){ printf("%.0f ",pow(2,getbits(n))); scanf("%d",&n); }
return0; }
int getbits(int n) { if(n==1)return0; int tmp=n,i=0,s[100]; for (i =0;i<100;i++)s[i]=-1; i =0; while(1){ if( (s[i++]=tmp%2) ==1)return i-1; tmp = tmp/2; } }
更强的一个解!使用按位运算的解法。明天再贴上关于按位运算的学习心得。(现在这段代码完全看不懂……)
#include <iostream> usingnamespace std; int main() ...{ int N; int res =1; while(1) ...{ cin >> N; if(N ==0) break; res =1; while((N &1) ==0) ...{ res *=2; N >>=1; } cout << res << endl; } return0; }