方法一:
时间复杂度:o(n)(n指的是变为二进制数后1所在的最高位位置,例如11–1011,就是4位)
这里不知道Integer.toBinaryString的性能
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
String s = Integer.toBinaryString(n);
int i = 0;
int num = 0;
while (i < s.length()){
char c = s.charAt(i);
if (c == '1'){
num++;
}
i++;
}
return num;
}
}
方法二:利用与运算逐位判断(来自力扣作者:jyd):每次都对最右边那一位进行判断,判断完就右移一位接着判断
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
}
方法三:消1法(作者同上):利用n&(n-1),可以将n最右边的1消掉,直到n=0为止
时间复杂度:o(M)(M指的是n中1的个数)
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
}