Count 1 in Binary
http://www.chenguanghe.com/lintcode-count-1-in-binary/
// no need to iterate all 32 bits
Count how many
1
in binary representation of a 32-bit integer.
上面程序中有三种方法,都来自编程之美
第一种:
第一种:
原数除以2后,数字将减少一个0
若余数是1则,减少一个1,记录1的个数
若余数是0则,减少一个0,记录0的个数
第二种:
利用位运算
0&1 =0
1&1 =1
这个32位数与0000 0001 与运算的值是1,记录1的个数
即:count += num & 0x01
num右移一位
num=num>>1
public int countOnes1(int num){ int count = 0; while(num!=0){ if(num%2==1) count++; num=num/2; } return count; } public int countOnes2(int num){ int count = 0; while(num!=0){ count +=num&0x01; num = num>>1; } return count; } public int countOnes3(int num){ int count = 0; while(num!=0){ num = num & (num-1); count++; } return count; }
// no need to iterate all 32 bits
public int countOnes(int num) {
int res = 0;
for(int i = 0 ; i < 32; i++) {
if((num & (1<<i)) != 0)
res++;
}
return res;
}
Read full article from Count 1 in Binary