任意給定一個32位無符號整數n,求n的二進制表示中1的個數,比如n = 5(0101)時,返回2,n = 15(1111)時,返回4
1 #include "stdafx.h"
2
3 //可能引起死循環,當n為負數時
4 int NumberOf1_Solution1(int n)
5 {
6 int count = 0 ;
7 while(n)
8 {
9 if(n & 1)
10 count++ ;
11 n = n >> 1;
12
13 // cout+=n&1;
14 // n >>=1;
15 }
16 return count ;
17 }
18
19 //循環次數等於整數二進制的位數
20 int NumberOf1_Solution2(int n)
21 {
22 int count = 0 ;
23 unsigned int flag = 1;
24 while(flag)
25 {
26 if(n & flag)
27 count ++ ;
28 flag = flag << 1;
29 // count +=n&flag?1:0;
30 // flag<<=1;
31 }
32 return count;
33 }
34
35 /*最佳方法 整數有幾個1就循環幾次
36 把一個整數減去1,再和原來整數做與運算,會把該整數最右邊一個1變成0。
37 那麼一個整數的二進制表示中有多少個1,就可以進行多少次這樣的操作。
38 */
39 int NumberOf1_Solution3(int n)
40 {
41 int count = 0 ;
42 while(n)
43 {
44 n = (n-1) & n ;
45 count ++ ;
46 }
47 return count ;
48 }
49
50 int main()
51 {
52 int number ;
53 printf("請輸入一個整數 (ctrl+z退出) :");
54 while(scanf("%d",&number) != EOF)
55 {
56 if(number >= 0)
57 printf("Solution1 is: %d\nSolution2 is: %d\nSolution3 is: %d\n",
58 NumberOf1_Solution1(number), NumberOf1_Solution2(number), NumberOf1_Solution3(number));
59 else //當number<0 時 只用方法2,3計算
60 printf("Solution2 is: %d\nSolution3 is: %d\n",NumberOf1_Solution2(number), NumberOf1_Solution3(number));
61
62 printf("請輸入一個整數 (ctrl+z退出) :");
63 }
64 return 0 ;
65 }
運算結果如下:
