描述
输入一个整数,输出该数32位二进制表示中1的个数。其中负数用补码表示。
示例1
输入:
10
复制返回值:
2
答案:简单运用移位操作,实现逐位判断
class Solution {
public:
int NumberOf1(int n) {
unsigned int m = n;
unsigned int len = 32, count = 0, temp;
while (len > 0) {
temp = m;
temp = (temp >> 1) << 1;
if (m > temp) {
count++;
}
m = m >> 1;
}
return count;
}
};
经过不断优化后,自认为性能最高的版本
class Solution {
public:
int NumberOf1(int n) {
unsigned int m = n;
int count = 0;
while (m!=0) {
count+=m&0x001;
m = m >> 1;
}
return count;
}
};