Reverse the Bits of a 32-bit Integer
Problem
Given a 32-bit unsigned integer n, return its bitwise reverse — bit i of the input becomes bit 31 − i of the output.
Input
n = 0b00000010100101000001111010011100Output
0b00111001011110000010100101000000Loop 32 times. Each step shifts the answer left, ORs in the lowest bit of n, then shifts n right.
def reverse_bits(n):
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return result
function reverseBits(n) {
let result = 0;
for (let i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n = n >>> 1;
}
return result >>> 0;
}
class Solution {
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>>= 1;
}
return result;
}
}
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1u);
n >>= 1;
}
return result;
}