problem
code
class Solution { public: int hammingWeight(uint32_t n) { int res = 0; while(n) { if(n%2) res++; n /= 2; } return res; } };
solution2
依据二进制数据的性质,使用模板进行实现。
class Solution { public: int hammingWeight(uint32_t n) { int bits = 0; int mask = 1; for(int i=0; i<32; i++) { if(n&mask) bits++; mask *=2; } return bits; } };