标签:
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide Tags Bit Manipulation
判断一个无符号整数中1的个数,这个问题很简单。将其与1做按位运算,并不断将整数右移,直到移位后的数字为0,就是下面的解法一。
如果上面不是判断一个无符号整数中1的个数而是有符号整数中1的个数,由于有符号整数右移时左边是根据符号位来补全的,这样对于负数而言会出现无穷的循环,所以不可以像上面那样对整数进行移位,但是可以对1进行移位,因为左移不存在按符号位补全的问题。循环的次数是sizeof(int)*8。即下面的解法二。
两种解法的runtime:4ms
class Solution {
public:
/**
* //解法一:移动数字本身,这种情况只对数字是无符号整型时才正确
int hammingWeight(uint32_t n) {
int base=1;
int result=0;
while(n)
{
if(n&base)
result++;
n>>=1;
}
return result;
}
*/
//解法二:移动基础的数字1,这种情况对于有符号和无符号数都成立
int hammingWeight(uint32_t n) {
int base=1;
int result=0;
for(int i=0;i<sizeof(uint32_t)*8;i++)
{
if(base&n)
result++;
base<<=1;
}
return result;
}
};
标签:
原文地址:http://blog.csdn.net/u012501459/article/details/46372251