题解 | #查找输入整数二进制中1的个数#
查找输入整数二进制中1的个数
http://www.nowcoder.com/practice/1b46eb4cf3fa49b9965ac3c2c1caf5ad
使用位操作,直接解决问题
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int i = sc.nextInt();
int bitCount = 0;
while (i > 0) {
//与 1 与操作,如果低端bit是1,结果就是1,是0的话,结果就是0
bitCount += i & 1;
i >>= 1;
}
System.out.println(bitCount);
}
sc.close();
} }
