Leetcode 191 Number of 1 Bits 位运算

统计一个值的二进制1的个数,用与(&)和向左移位(<<)

编程之美中的2.1节有详细解答。

解法一:

 1 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         int ans = 0;
 5         for(;n;n = n>>1){
 6             ans += n&1;
 7         }
 8         return ans;
 9     }
10 };

解法二:

 1 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         int ans = 0;
 5         for(;n;n &=(n-1)){
 6             ans ++;
 7         }
 8         return ans;
 9     }
10 };
原文地址:https://www.cnblogs.com/onlyac/p/5155996.html