Blind 75 · Bit Manipulation

Reverse Bits

Easy

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

Build the answer bit by bit: shift the result left to make room, take n's lowest bit into it, shift n right. Thirty-two rounds and the order is inverted. The signedness is the real content — in Java the int wraps into two's complement by itself, while Python's integers are unbounded, so a result at or above 2^31 must be converted by subtracting 2^32 to report the signed value.

Algorithm

1. Start the result at zero.
2. Thirty-two times: shift the result left, OR in n's lowest bit, shift n right.
3. In Python, convert a result at or above 2^31 into its signed reading.

Time & Space

Time O(32). Space O(1).