Skip to content

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).

Constraints:

  • The input must be a binary string of length 32.

Note:

  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

Example 1:

**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.

Solve


Python have a exact function int.bit_count() to do this task

class Solution:
    def hammingWeight(self, n: int) -> int:
        return n.bit_count()

Other than that could be: Turn any number to binary

class Solution:
    def hammingWeight(self, n: int) -> int:
        return bin(n)[2:].count("1")

While with C/C++, counting using bit manipulation

int hammingWeight(uint32_t n) {
    int count = 0;
    while (n != 0) {
        count += n & 1; // count = count + n % 2;
        n >>= 1; // n = n / 2
    }
    return count;
}

Time Submitted Status Runtime Memory Language
07/17/2023 22:33 Accepted 2 ms 5.5 MB c
07/17/2023 22:29 Accepted 47 ms 16.3 MB python3
07/17/2023 22:25 Accepted 41 ms 16.2 MB python3

Last update : October 13, 2023
Created : August 16, 2023