简单题,只要不断循环右移操作,并计算首位为1的情况有多少个
要注意的是Java中int类型是有符号的,因此如果使用 >> 那么在左边空位会以符号位补齐,当符号位为1时将陷入死循环。
所以要使用 >>> ,使得其以 0 补齐左边空位
自己的(0ms)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ans = 0;
while(n != 0){
int t = n & 1;
if(t == 1)
ans ++;
n = n >>> 1;
}
return ans;
}
}