输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
本题或者使用Java内置的Integer.toBinaryString方法将十进制数转化为2进制在一个个判断是否为1
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while (n != 0) {
count++;
n = n & (n - 1);
}
return count;
}
}