问题
编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数
例子
思路
-
方法1 O(logn)
-
方法2
代码
//方法1
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count=0;
while(n!=0){
count+=n&1;
//无符号右移:不管正负,高位补0
n=n>>>1;
}
return count;
}
}
//方法2