码迷,mamicode.com
首页 > 其他好文 > 详细

Lowest Bit

时间:2018-04-07 21:10:00      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:bre   ini   each   input   思路   nta   form   other   like   

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 }

 



Lowest Bit

标签:bre   ini   each   input   思路   nta   form   other   like   

原文地址:https://www.cnblogs.com/wkfvawl/p/8734411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!