Description
Given an positive integer A (1 <= A <= 100), 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 <= 100). 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 88 0
Sample Output
2 8
题目意思:我们知道十进制转化成二进制的方法,列如26,二进制则是11010,那么从后面开始算起只由第一位数是1的二进制是10,
其十进制则是2;同理88的
二进制则是1011000,从后面开始算起只由第一位数是1的二进制是1000,其十进制是8。
解题思路:要是直接从题目意思入手可以得到一下的代码:
1 #include<stdio.h> 2 #include<math.h>///类似十进制转换成二进制的原理,统计最后面的一个1之后0的个数 3 int lowest(int n) 4 { 5 int x,count=0; 6 while(n!=0) 7 { 8 x=n%2; 9 if(x==0) 10 count++; 11 else 12 break;///遇到非0就会退出 13 n=n/2; 14 15 } 16 return count; 17 } 18 int main() 19 { 20 int a,b; 21 while(scanf("%d",&a)!=EOF) 22 { 23 if(a==0) 24 break; 25 b=pow(2,lowest(a)); 26 printf("%d\n",b); 27 28 } 29 return 0; 30 }
其实还可以使用位运算的方法:
1 #include<stdio.h>///位运算的使用 2 int main() 3 { 4 int n,m; 5 while(scanf("%d",&n),n) 6 { 7 m=n&(n^(n-1)); 8 printf("%d\n",m); 9 } 10 return 0; 11 }