Coding Interview PatternsReverse Bits
EasyBitwise Manipulation
Reverse Bits
Explanation & Solution
Description
Reverse bits of a given 32-bit unsigned integer.
Note: In some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
Input: n = 43261596 (binary: 00000010100101000001111010011100)
Output: 964176192 (binary: 00111001011110000010100101000000)
Constraints
- The input must be a binary string of length
32
Approach
Bitwise Manipulation pattern
Key Insight
- Using
>>> 0at the end converts the result to an unsigned 32-bit integer, handling JavaScript's signed integer representation - Time: O(32) = O(1) | Space: O(1)