Reverse Bits

Easy

Problem

Reverse the order of the bits of a 32-bit unsigned integer and return the result as an unsigned integer.

Example 1

Input:  43261596 (00000010100101000001111010011100)
Output: 964176192 (00111001011110000010100101000000)

Test cases

Case 1

Input:    43261596
Expected: 964176192

Case 2

Input:    4294967293
Expected: 3221225471

Case 3

Input:    0
Expected: 0

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Shift out, shift in

Time O(32)Space O(1)

Take the lowest bit of n 32 times, appending it to the result. ">>> 0" keeps the result unsigned in JavaScript.

function reverseBits(n) {
let res = 0;
for (let i = 0; i < 32; i++) {
res = (res << 1) | (n & 1);
n >>>= 1;
}
return res >>> 0;
}