计算一个整数二进制中1的个数

这是来自牛客网关于一个二进制的运算

我的思路为每次和1 2 4 .....进行按位与运算就可得到二进制中1的个数

代码如下

 1 /*
 2  * *new coder ponint to offer 11
 3  * find bit 1 num of a nunber 
 4  */
 5 
 6 #include <stdio.h>
 7 #include <stdlib.h>
 8 
 9 int find1num(int number)
10 {
11     int i = 1,count = 0;
12 
13     //while( number / i != 0 ) //if number is negtive we will count error
14     
15     while( i != 0 )
16     {
17         if( (number & i) != 0)
18         {
19             count++;
20         }    
21 
22         i <<= 1; //i = i * 2
23     }
24     
25     return count;
26 }
27 
28 int main()
29 {
30 
31     int number;
32 
33     while(1)
34     {
35         scanf("%d",&number);
36         
37         int count = find1num(number);
38 
39         printf("num of bit 1 is : %d\n",count);
40     }
41 }

下面是另外一个大哥的思路,可以明显的减少循环的次数。思路为每次将整数和整数-1的数做与运算这样每次将整数最右边的1变成0,这样做的次数就是整数中含有1的个数,代码如下:

 1 /*
 2  * *new coder ponint to offer 11
 3  * find bit 1 num of a nunber
 4  * time best 
 5  */
 6 
 7 #include <stdio.h>
 8 #include <stdlib.h>
 9 
10 int find1num(int number)
11 {
12     int count = 0;
13 
14     
15     while( number != 0 )
16     {
17         count++;
18         number  = number & (number - 1); //every time do this will make the rightest 1 of number to 0 so we can do this opration the count 1 of number times
19     }
20     
21     return count;
22 }
23 
24 int main()
25 {
26 
27     int number;
28 
29     while(1)
30     {
31         scanf("%d",&number);
32         
33         int count = find1num(number);
34 
35         printf("num of bit 1 is : %d\n",count);
36     }
37 }

 

posted @ 2015-10-28 16:01  代码的搬运工  阅读(397)  评论(0编辑  收藏  举报