Reverse Bits
Reverse the order of the 32 bits of an int, so the bit at position 0 ends at position 31.
Given a 32-bit unsigned integer nnintint
Example 1
Output: 00111001011110000010100101000000 (964176192)
Example 2
Output: 10111111111111111111111111111111 (3221225471 unsigned, -1073741825 as a Java int)
The Idea
Reversing the digits of a number is something you could do on paper: 1230 read backwards is 0321. This problem asks for the same thing in binary, where every digit is a 0 or a 1, called a bit. A Java int
Look at the picture below. The row labelled "input n" is Example 1, 43261596, with all 32 bits written out and their positions above them. The row labelled "reversed" is the answer, 964176192. Bit 2 of the input is a 1, and it lands at position 29. Bit 0 is a 0, and it lands at position 31.
So, as the line under the picture says, a bit at position p ends at position 31 - p. The zeros on the left count too: the input starts with six zeros at positions 31 to 26, and in the answer those zeros fill positions 5 to 0.
How can a program move every bit to its mirror place? Working out 31 - p for each bit and setting the bit there would do it. But there is a simpler way, the same one you would use for the digits on paper.
To reverse 1230 by hand, take its last digit, 0, and write it down. Then take the next digit from the right, 3, and write it after the 0, then 2, then 1. Every digit written later pushes the earlier ones one place further left, so the last digit of 1230 ends up first.
Bits work the same way. Read the input from the right, one bit at a time, and append each bit to the right end of the answer. The bit read first, from position 0, is pushed left once by each of the 31 bits appended after it, so it lands at position 31.
Solution Approach
Three questions stand between the paper method and code: how to read the lowest bit of the input, how to append it to the answer, and how many times to repeat. Doing the work in fewer steps, for a method that is called very often, is an optional extra.
Reading the lowest bit
How do we read the bit at position 0? The &nn & 1nn & 1
To reach the next bit, shift nn >>>= 1
Why >>>>>intintint>>>>>n
Appending a bit to the result
How does a bit go onto the right end of the answer? Say the answer is built up in a variable named resultresult << 1result|(result << 1) | (n & 1)nresult
On a 4-bit number, 1011, the reading and appending go as in the table below.
| Step | Lowest bit of n | result after appending it | n after the shift |
|---|---|---|---|
| 1 | 1 | 1 | 101 |
| 2 | 1 | 11 | 10 |
| 3 | 0 | 110 | 1 |
| 4 | 1 | 1101 | 0 |
The final result
How many times to repeat
When can the loop stop? It looks tempting to stop once nnresultresultint
Fewer steps for many calls (optional)
What if the method is called millions of times? The 32-step loop is already a fixed amount of work, but there are ways to do fewer steps. A group of 8 bits is called a byte, and an intint
Java's own Integer.reverse(n)Integer.reverseBytesInteger.reverse(n)
Java Solution
The method reverseBits
- First, set
to 0. It collects the bits ofresult in reverse order.n - Run a
loop with a counterfor exactly 32 times, once per bit of ani .int - Inside the loop, append the lowest bit of
ton withresult .result = (result << 1) | (n & 1) - Then shift
right withn , so the next bit moves into position 0 and a 0 comes in on the left.n >>>= 1 - After 32 passes, every bit of
has been appended, and the method returnsn .result
Two small helpers handle the printing. The method bitsInteger.toBinaryStringshowint
The mainInteger.MIN_VALUEInteger.reverse
public class ReverseBits {
public static int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1); // append n's lowest bit to result
n >>>= 1; // unsigned shift: a 0 comes in on the left
}
return result;
}
// all 32 bits of x, leading zeros included
static String bits(int x) {
return String.format("%32s", Integer.toBinaryString(x)).replace(' ', '0');
}
static void show(int n) {
int r = reverseBits(n);
System.out.println(bits(n) + " -> " + bits(r) + " (" + r + ")");
}
public static void main(String[] args) {
show(0b00000010100101000001111010011100); // Example 1: 43261596
show(-3); // Example 2: 11...101
show(1);
show(0);
show(-1);
show(Integer.MIN_VALUE);
boolean same = true;
for (int n : new int[] {43261596, -3, 1, 0, -1, Integer.MIN_VALUE, 123456789}) {
same &= reverseBits(n) == Integer.reverse(n);
}
System.out.println("same as Integer.reverse: " + same);
}
}
Running it prints:
00000010100101000001111010011100 -> 00111001011110000010100101000000 (964176192)
11111111111111111111111111111101 -> 10111111111111111111111111111111 (-1073741825)
00000000000000000000000000000001 -> 10000000000000000000000000000000 (-2147483648)
00000000000000000000000000000000 -> 00000000000000000000000000000000 (0)
11111111111111111111111111111111 -> 11111111111111111111111111111111 (-1)
10000000000000000000000000000000 -> 00000000000000000000000000000001 (1)
same as Integer.reverse: true
Example 1 comes out as 00111001011110000010100101000000, which is 964176192. On the next line, -3 becomes 10111111111111111111111111111111. It prints as -1073741825 because its top bit is 1, and read as unsigned it is the 3221225471 of Example 2.
Look at the third line: the single 1 at position 0 ends at position 31, so the result is -2147483648. The line for Integer.MIN_VALUEInteger.reverse
A version that loops while (n != 0)>>>>>>>
Complexity
The work is one loop of 32 steps, whatever number comes in.
- Time: O(1), because the
loop always runs exactly 32 times, once per bit of anfor , with two shifts, an AND and an OR in each pass.int - Space: O(1), because the method keeps only
and the counterresult , and shifts its own copy ofi .n