统计二进制中1的个数
第一种方法
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) { // 输入一个整数
String str = Integer.toBinaryString(n);
int num = 0;
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(c=='1'){
num++;
}
}
return num;
}
}
第二种方法
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) { // 输入一个整数
return Integer.bitCount(n);
}
}


查看11道真题和解析