整数中1 的个数

问题

  求整数中1的个数

原理

  一个数n若不为0,从数的最低为到最高位,第一个为1 的位记为 i ,则减去 1 之后,改为变为0,i 右边的所有位都变为1,因此 n & (n-1)可得 n中剩余比 i 更高位序 的 部分 ,循环此操作,则可得 1 的计数。

代码 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int n,s,counter = 0;
 7     cout << " Please input a Integer : " ;
 8     cin >> n;
 9     s = n;
10 
11     while( n )
12     {
13         counter ++;
14         n = n & (n - 1);
15     }
16 
17     cout << " Number of One in " << s << " is " << counter << endl;
18 
19     return 0;
20 }

Output

 Please input a Integer : 20
 Number of One in 20 is 2

总结

  若是负数,则输出补码中包含 1 的个数。当然还有其他的方法: 初始化 1 ,让 1 依次循环左移,依次与 n 进行按位与操作,可得结果。

  

原文地址:https://www.cnblogs.com/with-a-orchid/p/NumberOfOneInInteger.html