Number of 1 Bits

Easy Bit Manipulation Tricks to remember Original on LeetCode

Number of 1 Bits is a easy bit manipulation problem solved with the tricks to remember pattern. The best approach, optimal (brian kernighan's trick), runs in O(number of set bits) time and O(1) space. Below are 2 approaches in Java, from check all 32 bits up.

Problem

Return the number of set bits (1s) in the binary representation of n (also called the Hamming weight).

Examples

Example 1

Input
n = 11
Output
3
Why
1011.

Example 2

Input
n = 128
Output
1

Constraints

  • 1 <= n <= 2^31 - 1

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.

ApproachTimeSpace
Check all 32 bitsO(32)O(1)
Optimal (Brian Kernighan's trick)O(number of set bits)O(1)

1Check all 32 bits

TimeO(32)
SpaceO(1)

Test the lowest bit and shift right, 32 times (or until n is 0).

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

2Optimal (Brian Kernighan's trick)

TimeO(number of set bits)
SpaceO(1)

n - 1 flips the lowest set bit and every bit below it, so n & (n - 1) removes exactly the lowest set bit. The loop runs once per set bit.

  1. while n != 0: n &= n - 1; count++.
Java
class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n &= n - 1;
            count++;
        }
        return count;
    }
}

Edge cases to test

  • Powers of two (1)
  • 2^31 - 1 (31 ones)

Hints

Hint 1

n & (n - 1) clears the lowest set bit. Count how many times you can do it before n becomes 0.

FAQ

What is the best time complexity for Number of 1 Bits?

Optimal (Brian Kernighan's trick) runs in O(number of set bits) time and O(1) extra space.

Which pattern does Number of 1 Bits use?

It is a bit manipulation problem that uses the tricks to remember pattern. Other problems with the same pattern: Set the rightmost unset bit, XOR of 1 to n Numbers.

Is there a brute force solution for Number of 1 Bits?

Yes. Check all 32 bits takes O(32) time and O(1) space. Test the lowest bit and shift right, 32 times (or until n is 0).

Which edge cases should I test for Number of 1 Bits?

Powers of two (1); 2^31 - 1 (31 ones).