计算一个正数的二进制表示中有多少位1

 1 #include <iostream>
 2 #include <bitset>
 3 using namespace std;
 4 
 5 class BitCount
 6 {
 7 public:
 8     size_t Count1(size_t n)
 9     {
10         size_t counts = 0;
11 
12         while (n > 0)
13         {
14             counts += (n & 1);
15             n >>= 1;
16         }
17 
18         return counts;
19     }
20 
21     size_t Count2(const size_t n)
22     {
23         constexpr size_t N = sizeof(n);
24         std::bitset<N> tmp(n);
25 
26         return tmp.count();
27     }
28 };
29 
30 int main()
31 {
32     BitCount bc;
33 
34     cout << bc.Count1(6) << endl;
35     cout << bc.Count2(6) << endl;
36 
37     return 0;
38 }

 

posted @ 2016-08-04 23:16  Ricardo  阅读(198)  评论(0编辑  收藏  举报