191。Number of1 Bits

偏执的太偏执、 2022-06-10 14:41 308阅读 0赞

/*
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.
*/

#define max 1010
int hammingWeight(uint32_t n) {
uint32_t i,count = 0,temp = n;
int a[max] = {0};
for(i = 0 ; n!= 0 ; i++)
{
a[i] = n % 2;
n = n / 2;
}
for(i=0;temp != 0;i++)
{
temp = temp / 2;
if(a[i]==1)
count++;
}
return count;
}

发表评论

表情:
评论列表 (有 0 条评论,308人围观)

还没有评论,来说两句吧...

相关阅读

    相关 #191 Number of 1 Bits

    没有找到数算书。。摸了一本C++ Primer过来。再从网上学学吧~ 今天还是看看简单题好了,哪里不会学哪里。 挑一道看起来就简单的嘿嘿。 [\191 Number of