原题链接:191. Number of 1 Bits
【思路】
运用位运算中的一个技巧n &= (n - 1)可以将最右边的一个1置0后返回给n
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
while (n != 0) {
n = n & (n - 1);
res++;
}
return res;
}
600 / 600
test cases passed. Runtime: 2 ms Your runtime beats 12.55% of javasubmissions.