LN : leetcode 191 Number of 1 Bits

lc 191 Number of 1 Bits


191 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.

analysation##

如果当前的数据为有符号数,在进行右移的时候,根据符号位决定左边补0还是补1。如果符号位为0,则左边补0;但是如果符号位为1,则根据不同的计算机系统,可能有不同的处理方式。

将所有对2的整除运算转换为位移运算,可提高程序的运行效率。

soliution

int hammingWeight(uint32_t n) {
int t, sum = 0;
for (t = 31; t >= 0; t--) {
if ((n >> t & 1) == 1)
sum++;
}
return sum;
}
上一篇:SQL SERVER HTTP请求


下一篇:Leetcode#191. Number of 1 Bits(位1的个数)