191 Number of 1 Bits 位1的个数

编写一个函数,输入是一个无符号整数,返回的是它所有 位1 的个数(也被称为汉明重量)。
例如,32位整数 '11' 的二进制表示为 00000000000000000000000000001011,所以函数返回3。

详见:https://leetcode.com/problems/number-of-1-bits/description/

Java实现:

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int cnt=0;
        while(n!=0){
            n=(n-1)&n;
            ++cnt;
        }
        return cnt;
    }
}

C++实现:

方法一:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int cnt=0;
        unsigned int flag=1;
        while(flag)
        {
            if(flag&n)
            {
                ++cnt;
            }
            flag<<=1;
        }
        return cnt;
    }
};

 方法二:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int cnt=0;
        while(n)
        {
            n=(n-1)&n;
            ++cnt;
        }
        return cnt;
    }
};
原文地址:https://www.cnblogs.com/xidian2014/p/8745457.html