请实现一个函数,输入一个整数,输出该数二进制表示中1的个数
例如:9的二进制表示为1001,有2位是1
先看结果:输入9 输出它的二进制 运用位运算方法&与,得出1有两位
9
1001
2
2
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
System.out.println(Integer.toString(N, 2));
int count = 0;
for (int i = 0; i < 32; i++) {
// 比对每一位
if ((N & (1 << i)) == (1 << i)) {
count++; // 第一种方法
}
}
System.out.println(count);
count = 0;
while (N != 0) {
N = ((N - 1) & N); // &与
count++; // 第二种方法
}
System.out.println(count);
}