题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
代码示例
public class Offer10 {
public static void main(String[] args) {
int num1 = 0b11010011;
Offer10 testObj = new Offer10();
System.out.println(testObj.numberOf1(num1));
System.out.println(testObj.numberOf1_2(num1));
}
//法1:
public int numberOf1(int num) {
int count = 0;
while (num != 0) {
count++;
num &= (num - 1);
}
return count;
}
//法2:
public int numberOf1_2(int num) {
return Integer.bitCount(num);
}
}