美文网首页
191. Number of 1 Bits

191. Number of 1 Bits

作者: SilentDawn | 来源:发表于2018-07-11 11:28 被阅读0次

    Problem

    Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

    Example

    Input: 11
    Output: 3
    Explanation: Integer 11 has binary representation 00000000000000000000000000001011 
    
    Input: 128
    Output: 1
    Explanation: Integer 128 has binary representation 00000000000000000000000010000000
    

    Code

    static int var = [](){
        std::ios::sync_with_stdio(false);
        cin.tie(NULL);
        return 0;
    }();
    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int count = 0;
            while(n!=0){
                count += n % 2;
                n = n/2;
            }
            return count;
        }
    };
    

    Result

    191. Number of 1 Bits.png

    相关文章

      网友评论

          本文标题:191. Number of 1 Bits

          本文链接:https://www.haomeiwen.com/subject/flfhpftx.html