Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
找出二进制数中1的个数,利用n & (n - 1)求解即可。
class Solution { public: int hammingWeight(uint32_t n) { int res = 0; while (n) { n &= (n - 1); res++; } return res; } }; // 3 ms
也可以用二进制数的最后一位&1,计算1的个数。然后把二进制数右移一位。直到n变为0。
class Solution { public: int hammingWeight(uint32_t n) { int res = 0; while (n) { res += (n & 1); n >>= 1; } return res; } }; // 3 ms