题目:
计算在一个 32 位的整数的二进制表式中有多少个 1.
样例:
给定 32 (100000),返回 1
给定 5 (101),返回 2
给定 1023 (111111111),返回 9
解法一:
/**
* @param num: an integer
* @return: an integer, the number of ones in num
*/
static int count;//1的个数
public int countOnes(int num) {
// write your code here
while( num != 0 ){
if( (num & 1) == 1)
count++;
num = num>>1;//将num右移一位
}
return count;
}
解法一的缺陷就是:必须要循环32次才能得出1的个数,所以时间复杂度比较高。
解法二:
static int count;//1的个数
public int countOnes(int num) {
for(count = 0 ; num != 0 ; count++ ){
num = num & (num -1);
}
return count;
}
解法二思路:
为什么n &= (n – 1)能清除最右边的1呢?因为从二进制的角度讲,n相当于在n - 1的最低位加上1。举个例子,8(1000)= 7(0111)+ 1(0001),所以8 & 7 = (1000)&(0111)= 0(0000),清除了8最右边的1(其实就是最高位的1,因为8的二进制中只有一个1)。再比如7(0111)= 6(0110)+ 1(0001),所以7 & 6 = (0111)&(0110)= 6(0110),清除了7的二进制表示中最右边的1(也就是最低位的1)。