题:
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进行计数。
solution:
这道题主要一个陷阱就是,题目要求计算的是该整数无符号二进制中的1的个数,但是整数实际上在计算机中是按照有符号二进制补码存储会有一位符号位,所以当输入为
231
时,其无符号二进制是100000000000000000000000000000000,但是你转换出来是011111111111111111111111111111111,因为溢出了.
我们只需要把输入的32位无符号整数用long类型存储,这样可以避免数据位被转化成符号位。
class Solution {
public:
int hammingWeight(uint32_t n) {
long m = n;
int count=0;
int i=0;
while((m>>i)>0)
{if((m>>i)&1==1)count++;i++;}
return count;
}
};