Categories:

Tags:



Problem

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

Follow up: If this function is called many times, how would you optimize it?

Constraints

  • The input must be a binary string of length 32

Solution

The problem Number of 1 Bits can be solved by iterating through all 32 bits and all bits.

Implementation

class Solution
{
  public:
    int hammingWeight(uint32_t n)
    {
        int ret = 0;
        for (int i = 0; i < 32; i++)
            ret += (n >> i) & 1;
        return ret;
    }
};