Reverse Bits
Easy · Bit Manipulation
You are given a 32-bit unsigned integer. Return the integer that results from reversing the order of its bits, treating the number as a fixed-width 32-bit binary string. The most significant bit becomes the least significant bit and vice versa.
Examples
Input: n = 43261596 (binary 00000010100101000001111010011100)
Output: 964176192 (binary 00111001011110000010100101000000)
Why: Reading the 32-bit binary representation backwards gives the binary representation of 964176192.
Input: n = 4294967293 (binary 11111111111111111111111111111101)
Output: 3221225471 (binary 10111111111111111111111111111111)
Why: Flipping the bit order of the 32-bit pattern moves the single 0 bit from position 1 to position 30 from the end.
Input: n = 0
Output: 0
Why: All 32 bits are 0, so reversing them still gives all zeros.
Constraints
n is given as an unsigned 32-bit integer, 0 <= n <= 2^32 - 1
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Reverse Bits. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.