剑指Offer08 二进制中1的个数

 1 /*************************************************************************
 2     > File Name: 08_NumOf1InBinary.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年08月29日 星期一 20时40分15秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9  
10 int NumberOf1_1(int n)
11 {
12     int count = 0;
13     int flag = 1;
14     while (flag < n)
15     {
16         if (n & flag)
17             count ++;
18         flag = flag << 1;
19     }
20     return count;
21 }
22 
23 int NumberOf1_2(int n)
24 {
25     int count = 0;
26     while (n)
27     {
28         ++ count;
29         n = (n - 1) & n;
30     }
31     return count;
32 }
33 
34 int main()
35 {
36     int ret1 = 0;
37     int ret2 = 0;
38     
39     int n = 5;
40     ret1 = NumberOf1_1(n);
41     ret2 = NumberOf1_2(n);
42     printf("ret1 is %d
", ret1);
43     printf("ret2 is %d
", ret2);
44 }
原文地址:https://www.cnblogs.com/Juntaran/p/5819619.html