题目链接:https://leetcode.com/problems/number-of-1-bits/
题目描述:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
刚做完第190题reverse bits,再做这道,就会觉得很简单了,同样是一道位操作的题。
思路是这样的,将源操作数循环右移,然后和1进行“与运算”,结果为1,计数器就加1,直到n移位后的结果为0,即可跳出循环。
代码如下:
<span style="font-size:12px;">int hammingWeight(uint32_t n) {
int count = 0;
while (n != 0){ //n等于0,跳出循环
if( n & 1){ //同1做与运算,结果为1,则最右位为1,计数器加1
count++;
}
n >>= 1;
}
return count;
}</span>
这么简单就结束了?感觉很诡异的样子,这道题其实在Brian W. Kernighan和Dennis M. Ritchie写的C程序设计语言中是道例题,并在例题中给出了 x &= (x-1)的提示,即:
在求对二的补码时,表达式 x &= (x-1)可以删除x中最右边值为1的一个二进制位。
原理是,x-1使得x最右边值为1的位变为0;再与x本身相与后,x最右边值为1的位变为0,此为之前的位(左边的位)的值不变。
所以可以用 x &= (x-1)加快执行速度,代码如下:
<span style="font-size:12px;">int hammingWeight(uint32_t n) {
int count = 0;
if(n > 0){ //这里要考虑边界值0,因为0-1之后就为负数了,不同的编译器会有问题,所以要从1开始。
count++; //这里要先对count进行一次加1操作,因为while循环在最后一个值为1的位时就不进入循环体了,相当于少算了一次,在这里补上。
while (n &= (n-1)){
count++;
}
}
return count;
}</span>