LeetCode 191: Number of 1 Bits

Problem Description

Explanation:

To find the number of set bits in the binary representation of a positive integer n, we can use the bitwise AND operation with 1 to check the least significant bit. If the result is 1, we increment a counter. We then right shift the number by 1 bit to move to the next bit. We repeat this process until the number becomes 0.

Time complexity: O(log n) - where n is the input number
Space complexity: O(1)

Solutions

public int hammingWeight(int n) {
    int count = 0;
    while (n != 0) {
        count += n & 1;
        n >>>= 1;
    }
    return count;
}

Loading editor...