Reverse Bits Explained
Problem Statement
Given a 32-bit unsigned integer n
, reverse its bits and return the result as an unsigned integer. For example, if the input is 43261596 (binary: 00000010100101000001111010011100), the output is 964176192 (binary: 00111001011110000010100101000000). This problem tests your ability to manipulate individual bits using shifts and bitwise operations to achieve the reversal.
Example
Input: n = 43261596
Output: 964176192
Explanation: The 32-bit binary representation of 43261596 is reversed to produce 964176192.
Code
Java
Python
JavaScript
public class Solution { public int reverseBits(int n) { int result = 0; for (int i = 0; i < 32; i++) { result <<= 1; result |= (n & 1); n >>>= 1; } return result; } public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.reverseBits(43261596)); // 964176192 } }
def reverse_bits(n): result = 0 for _ in range(32): result <<= 1 result |= (n & 1) n >>= 1 return result # Example usage print(reverse_bits(43261596)) # 964176192
function reverseBits(n) { let result = 0; for (let i = 0; i < 32; i++) { result <<= 1; result |= (n & 1); n >>>= 1; } return result >>> 0; } // Example usage console.log(reverseBits(43261596)); // 964176192
Explanation
- Initialize
result
to 0 to build the reversed bits. - For each of the 32 bits:
- Left-shift
result
by 1 to make space for the next bit. - Extract the least significant bit of
n
usingn & 1
and OR it intoresult
. - Right-shift
n
by 1 to process the next bit. - Return the final
result
.
Note
The time complexity is O(1) since exactly 32 iterations are performed. In JavaScript, use
>>> 0
to ensure the result is an unsigned 32-bit integer. Be cautious with languages that don’t enforce 32-bit integers, like Python.