剑指 Offer 15. 二进制中1的个数
思路
代码实现
方法一:
1 class Solution { 2 public: 3 int hammingWeight(uint32_t n) { 4 int ans = 0; 5 while(n != 0) { 6 ans += (n & 1); 7 n = n >> 1; 8 } 9 10 return ans; 11 } 12 };
方法二:
1 class Solution { 2 public: 3 int hammingWeight(uint32_t n) { 4 int ans = 0; 5 while(n != 0) { 6 ans++; 7 n &= n-1; 8 } 9 10 return ans; 11 } 12 };