> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Number of 1 Bits

Leetcode Problem 191: Number of 1 Bits

Problem Summary

Given a positive integer n, return the number of set bits (bits with value 1) in its 32-bit binary representation. This count is also known as the Hamming weight or popcount.

For example, integer 11 has binary representation 00000000000000000000000000001011, which contains 3 set bits.

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

Constraints:

  • The input is a positive integer in the range [1, 2^31 − 1].

Techniques

  • Divide and Conquer
  • Bit Manipulation

Solution

function hammingWeight(n: number): number {
    let number = 0

    for (let i = 0; i < 32; i++) {
        number = number + (n & 1)
        n = n >>> 1
    }

    return number
}

console.log(hammingWeight(2147483645))