Count how many 1 in binary representation of a 32-bit integer.
Example
Given 32, return 1
Given 5, return 2
Given 1023, return 9
Challenge
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
v1:直觉第一反应就是无非就是2进制转换,然后统计1的个数。
int countOnes(int num) {
// write your code here
int count = 0;
while(num > 0){
int mod = num % 2;
if(mod == 1)count++;
num /= 2;
}
return count;
}
v2:事实证明并不是这样,因为负数同样会以补码形式存在,所以才去按位和1相与的操作取每一数然后进行统计
int countOnes(int num) {
// 通过与1相与按位取出所有位,然后统计即可
int count = 0;
for(int i = 0; i < 32; i++){
if(((num >> i) & 1) == 1){
count++;
}
}
return count;
}