191. Number of 1 Bits

 1 class Solution 
 2 {
 3 public:
 4     int hammingWeight(uint32_t n) 
 5     {
 6         int count=0;
 7         while(n)
 8         {
 9             count+=n&1;
10             n>>=1;
11         }
12         return count;
13     }
14 };

把末尾的位摘下来直接累加就行,直到原数字因为右移操作变为0。

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9071275.html