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
Example 1
Output: 3
Example 2
Output: 1
Example 3
Output: 31
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
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 intint
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 nn - 1&
In the row labelled pass 1, nn - 1
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 nn & (n - 1)
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 & 1n
The shift has to be >>>>>>>>>>>>n
Clearing one bit per pass
How does the faster loop look? While nn & (n - 1)
Negative numbers
Does the loop work when nn != 0n > 0n > 0n != 0
The trickiest value is Integer.MIN_VALUEintInteger.MAX_VALUE
Letting Java count (optional)
Is there a ready-made method? Integer.bitCount(n)Long.bitCountlong
Java Solution
The method hammingWeight
- First, start a counter,
, at 0.count - Run a
loop as long aswhile is not 0. In each pass, clear the lowest 1 bit withn , which is short forn &= n - 1 .n = n & (n - 1) - In the same pass, add 1 to
for the bit just cleared.count - Once
is 0, every 1 bit has been cleared exactly once, son holds how many there were, and the method returns it.count
The mainInteger.MIN_VALUE0bInteger.toBinaryStringInteger.bitCount
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:
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
The line 0 = 0 -> 0intInteger.MIN_VALUEn - 1Integer.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
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.int - Space: O(1), because the method changes its own copy of
and keeps nothing butn .count
The same n & (n - 1)