Number of 1 Bits

来源:互联网 发布:季后赛马刺vs雷霆数据 编辑:程序博客网 时间:2024/06/03 22:07
问题描述:
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.
解题思路:
计算数值n的32位2进制表示有多少位1,可以考虑设置变量k左移位判断,有则加1,
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int sum=0;
        for(unsigned long k=1;k<pow(2.0,32);k=k<<1)
        {if((n&k)==k)
          sum++;
        }
        return sum;
    }
};
另外一种简洁方法如下:
public class Solution {
    public int hammingWeight(int n) {
        int re = 0;
        while(0 != n)
        {
            n = n&(n - 1);//每比较一次n上最低位1被设置为0
            ++re;
        }
        return re;
    }
}
0 0
原创粉丝点击