Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
首先,第一种思路应该是将整数与1相与,向右移位,计算number。但是如果整数是负数,会产生死循环。
针对第一种思路的优化是,不再对整数向右移位,与1相与,对1进行向左移位。
第三种是一种更好地办法。一个结论:将整数减去1,与原整数相与,会将该整数最右边的1变成0。
例如:(1)当该整数二进制最右边数字为1时,如1111,减去1变成1110,最右端1变成0。
(2)当该整数的二进制表示最右端的1为倒数第n位,减1后倒数第n位变为0,倒数第n位右边的0全部变为1。
则 整数 m & (m-1) 会将m的最右端的1置为0。 则该整数二进制表示中有几个1就循环几次即可。
int hammingWeight(uint32_t n) {
int count = 0;
while(n)
{
++count;
n = n & (n-1);
}
return count;
}