输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
思路:考虑n = n & (n-1) 表示把n的二进制数字最右边的为1的数字变成0。那么n有多少个二进制位1,就可以进行多少次这样的操作。
class Solution {
public:
int NumberOf1(int n) {
int res = 0;
while(n) {
n = n & (n-1);
++res;
}
return res;
}
};