Blind 75 · Bit Manipulation

Reverse Bits

Easy

Watch the walkthrough (5:26)

Problem

Take a non-negative integer n, read its 32 bits, and write them down in reverse order — bit 0 becomes bit 31 and so on.
Return the result interpreted as a signed 32-bit two's-complement integer. That interpretation matters: reversing 1 sets the sign bit, so the answer is -2147483648, a negative number.

Examples

Example 1:
Input: n = 43261596
Output: 964176192
Explanation: 00000010100101000001111010011100 reversed is 00111001011110000010100101000000.

Example 2:
Input: n = 1
Output: -2147483648
Explanation: the lone bit lands on the sign position.

Example 3:
Input: n = 0
Output: 0

Example 4:
Input: n = 4
Output: 536870912

Constraints

0 <= n <= 2^31 - 1

Prerequisites

Binary and two's complement — how a negative number is stored, and what a shift does at the edges.
The trick worth memorising: n & (n-1) clears the lowest set bit.

How to think about it

1. Shift Out, Shift In Optimal

Intuition

Reversing is a mirror: bit i of n goes to bit 31 - i of the answer, so 4 = 100, whose one set bit is bit 2, becomes bit 29, 536870912. The places need no working out. Take n's last bit, make room in the answer by shifting it left, put the bit in, and shift n right: the first bit taken climbs one place every round after it, so after 32 rounds it is bit 31, and every bit is where the mirror puts it. Then read the answer signed. Bit 31 is the sign bit: Java's int reads it that way by itself, and Python's int has no 32-bit limit, so an answer of 2^31 or more has 2^32 taken off. 11 = 1011 becomes 11010000000000000000000000000000, which is 3489660928 read unsigned and -805306368 read signed. Shift each bit off the input's low end and onto the answer's low end.

Algorithm

1. Start the result at 0.
2. 32 times: shift the result left by one and OR in n's last bit, n & 1; then shift n right by one (in Java, >>>).
3. Return the result read signed: in Java it already is; in Python, take 2^32 off a result of 2^31 or more.

Time & Space

Time O(1): always 32 rounds. Space O(1).