AlgoInsight

DSA problem

Reverse Bits

EasyBit ManipulationPattern: Bit Manipulationtop300AmazonAppleAirbnb

Reverse the bits of a given 32-bit unsigned integer.

Given a 32-bit unsigned integer n, return the integer obtained by reversing the order of its 32 bits, so that the most significant bit becomes the least significant bit and vice versa.

The standard approach scans the input one bit at a time from the least significant end. For each of the 32 positions, the lowest bit of n is extracted with n & 1, the running result is shifted left to make room, and the extracted bit is appended. After 32 iterations, the bits originally at the low end have been pushed all the way to the high end.

Note that in some languages integers are signed, so the reversed value may appear negative when its top bit is set; the underlying 32-bit pattern is still correct.

Examples

Example 1
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input represents 43261596. Reversing all 32 bits yields the pattern 00111001011110000010100101000000, which equals 964176192.
Example 2
Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input represents 4294967293. Reversing the 32 bits produces 10111111111111111111111111111111, which equals 3221225471.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bit-manipulationdivide-and-conquer

Browse all DSA problems