Number of 1 Bits(计算一个数中有多少位为1)

来源:互联网 发布:淘宝专柜代购5折可信吗 编辑:程序博客网 时间:2024/05/16 19:39

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

method:

这一题比较简单,很容易想到位的偏移(主要是前天看源码,内存页的存取各种offset看到晕—。—)

<span style="font-size:18px;">int hammingWeight(uint32_t n) {    int j = 0;    int count = 0;    for (j; j< 32;j++)    {        if((1<<j)&n)        {            count++;        }    }    return count;}</span>


0 0
原创粉丝点击