Number of 1 Bits

Count how many of the 32 bits of a Java int are 1, clearing one 1 bit per pass.

Given a 32-bit integer n, return how many of its 32 bits are 1. A negative number counts its bits the same way as any other. This count is also called the Hamming weight or population count of the number.

Example 1
Input: n = 11 (binary 1011)
Output: 3
Example 2
Input: n = 128 (binary 10000000)
Output: 1
Example 3
Input: n = 11111111111111111111111111111101 (binary)
Output: 31
Solution

The Idea

Picture a row of 32 light switches, numbered from 0 on the right to 31 on the left, each either off or on. A Java int is stored just like that, as 32 bits that are each 0 or 1. The problem asks how many switches are on.

Each position stands for a power of two: position 0 is worth 1, position 1 is worth 2, position 2 is worth 4, and position 3 is worth 8. Writing a number as the positions that add up to it gives its binary form. In Example 1, 11 is 8 + 2 + 1, so positions 3, 1 and 0 are on, and the bits read 1011. The 28 bits above position 3 are all 0, so the answer is 3. In Example 2, 128 is the power of two at position 7, so one bit is on.

Example 3 has every bit set except position 1. A Java int is 32 bits in two's complement, the way Java writes negative numbers: to get -3, take the bits of 3, flip every one of them, and add 1. That turns 000...011 into 111...100 and then 111...101, the bits of Example 3. The leftmost bit, position 31, is 1 for every negative int and is called the sign bit. It is counted like any other, so the answer is 31.

The plain way to count looks at all 32 positions, one after another. For 128 that is 32 looks to find a single bit that is on. So a question comes up: can we jump straight from one 1 bit to the next and skip the 0s in between?

Subtracting 1 can do that. In decimal, 1000 - 1 = 999: the last nonzero digit goes down by one, and every 0 after it turns into 9. Binary works the same way. The lowest 1 bit becomes 0, every 0 below it becomes 1, and the bits above it stay as they were.

Now combine n and n - 1 with Java's & operator, called AND. It compares the two numbers position by position and gives 1 only where both have a 1. The bits above the lowest 1 are the same in both numbers, so they stay. From the lowest 1 down, one of the two numbers has a 0 in every position, so those bits all become 0. Look at the picture below.

Counting the 1 bits of 11, binary 1011. Each pass computes n & (n - 1), which clears the lowest 1 bit: 1011 becomes 1010, then 1000, then 0000. Three passes, so the count is 3.

In the row labelled pass 1, n is 1011, and its lowest 1 bit, in orange, is at position 0. Subtracting 1 flips just that bit, shown in teal, so n - 1 is 1010, and the AND gives 1010, which is 10. In pass 2, the lowest 1 is at position 1. Subtracting 1 flips positions 1 and 0 to give 1001, and the AND leaves 1000, which is 8.

In pass 3, 1000 - 1 flips all four bits shown, to 0111, and the AND leaves 0000. Each pass removed exactly one 1 bit, so the number of passes until n reaches 0 is the answer: 3, as in the count column. This step, n & (n - 1), is often called Brian Kernighan's trick.

Solution Approach

Turning that idea into code means settling three things: what the plain bit-by-bit count costs, how the loop clears bits and when it stops, and how negative numbers behave. Letting Java count the bits comes last, as an optional extra.

Checking every bit

What does the plain way look like? The expression n & 1 gives the bit at position 0, and shifting n one place to the right moves the next bit into position 0. Doing that 32 times and adding up the bits gives the count; for -3 it gives 31. It always takes 32 steps, even for 128 with its single 1 bit.

The shift has to be >>>, which brings in a 0 from the left. The other right shift, >>, copies the sign bit in from the left instead. Starting from -3, 32 shifts with >>> give 0, but with >> the value gets stuck at -1, all ones. A loop that shifts with >> until n is 0 would never end for a negative number.

Clearing one bit per pass

How does the faster loop look? While n is not 0, replace it with n & (n - 1) and add 1 to a counter. Each pass removes one 1 bit, so the loop runs once per 1 bit instead of once per position. Example 1 takes 3 passes and Example 2 takes 1, where the plain way took 32 each time.

Negative numbers

Does the loop work when n starts out negative? The stop condition must be n != 0, not n > 0. With n > 0, -3 never enters the loop and the method returns 0 instead of 31. With n != 0, the passes keep clearing bits, and the sign bit is cleared like the rest once it is the lowest 1 left.

The trickiest value is Integer.MIN_VALUE, -2,147,483,648, whose bits are a 1 at position 31 and 31 zeros. Subtracting 1 goes past the smallest int and wraps around to Integer.MAX_VALUE, 2,147,483,647: a 0 at position 31 and 31 ones. That is exactly the pattern from the picture, the lowest 1 turned to 0 and the bits below it turned to 1, so the AND gives 0 and the count is 1.

Letting Java count (optional)

Is there a ready-made method? Integer.bitCount(n) returns the same count, and Long.bitCount does the same for a 64-bit long. In real code, use it; the loop shows how the count works.

Java Solution

The method hammingWeight works in these steps:

  1. First, start a counter, count, at 0.
  2. Run a while loop as long as n is not 0. In each pass, clear the lowest 1 bit with n &= n - 1, which is short for n = n & (n - 1).
  3. In the same pass, add 1 to count for the bit just cleared.
  4. Once n is 0, every 1 bit has been cleared exactly once, so count holds how many there were, and the method returns it.

The main method runs the three examples, then 0, -1 and Integer.MIN_VALUE. Example 3 is written with the prefix 0b, which tells Java the digits are binary. For each it prints the number, its bits from Integer.toBinaryString (which leaves out leading zeros), the count, and what Integer.bitCount gives.

Java
public class NumberOf1Bits {

    public static int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n &= n - 1;          // clear the lowest 1 bit
            count++;
        }
        return count;
    }

    static void show(int n) {
        System.out.println(n + " = " + Integer.toBinaryString(n) + " -> " + hammingWeight(n)
                + " (Integer.bitCount: " + Integer.bitCount(n) + ")");
    }

    public static void main(String[] args) {
        show(11);
        show(128);
        show(0b11111111111111111111111111111101);   // -3 as a Java int
        show(0);
        show(-1);
        show(Integer.MIN_VALUE);
    }
}

Running it prints:

Output
11 = 1011 -> 3 (Integer.bitCount: 3)
128 = 10000000 -> 1 (Integer.bitCount: 1)
-3 = 11111111111111111111111111111101 -> 31 (Integer.bitCount: 31)
0 = 0 -> 0 (Integer.bitCount: 0)
-1 = 11111111111111111111111111111111 -> 32 (Integer.bitCount: 32)
-2147483648 = 10000000000000000000000000000000 -> 1 (Integer.bitCount: 1)

Look at the third line. The bits from Example 3 print as the number -3, which is the two's complement reading of those bits, and the count is 31. For 11 and 128, toBinaryString drops the leading zeros, while for the negative numbers it shows all 32 bits, because position 31 is set.

The line 0 = 0 -> 0 is the case where the loop never runs. Next, -1 has all 32 bits set and takes 32 passes, the most any int can need. The last line is Integer.MIN_VALUE, with only the sign bit set, and its count is 1 even though n - 1 wrapped around. In every line, the count matches Integer.bitCount.

Complexity

The loop runs once per 1 bit, and each pass is one subtraction, one AND and one addition.

  • Time: O(k) for an int with k bits set to 1, because each pass clears exactly one of them, so 11 takes 3 passes and -1 takes the most, 32.
  • Space: O(1), because the method changes its own copy of n and keeps nothing but count.

The same n & (n - 1) step answers Power of Two: a power of two has a single 1 bit, so clearing it leaves 0.