LeetCode: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.


思路:

1、十进制变为二进制,经典解法;

2、求余除2依次得到2进制存入数组中;

3、统计数组中1的个数。

代码:

class Solution {
public:
    int hammingWeight(uint32_t n) {
    if(n == 0)
    {
        return 0;
    }
    int array[32] = {0};
    int i = 0;
    while(n)
    {
        array[i++] = n % 2;
        n = n / 2;
    }
    int count = 0;
    for(int j = 0; j < 32; ++j)
    {
        if(array[j] == 1)
        {
            ++count;
        }
    }
    return count;
    }
};


你可能感兴趣的:(LeetCode,C++)