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

  • Time: O(1)
  • Space: O(1)
public int hammingWeight(int n) {
    int count = 0;
    for (int i = 1; i <= 32; i++) {
        if ((n & (1 << i)) != 0) {
            count++;
        }
    }
    return count;
}

results matching ""

    No results matching ""