题目提示里说了输入长度是32位的二进制,因此把n右移32次(从0开始),每次都和1进行“与”运算, 值为1说明含有1。
代码:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for (int i = 0; i < 32; i++) {
if (((n >>> i) & 1) == 1) {
count++;
}
}
return count;
}
}