Reverse Bits

EasyBit manipulation

Given an unsigned 32-bit integer n, reverse the order of its 32 bits, so bit 0 becomes bit 31 and bit 31 becomes bit 0, and return the result as an unsigned number.

JavaScript has no unsigned 32-bit type, so n arrives as an ordinary number from 0 to 4294967295 (2³² − 1), and the answer must be in that range too. The bitwise operators give signed 32-bit results; x >>> 0 turns one back into an unsigned number.

Examples

Example 1
Input:  n = 1
Output: 2147483648

Bit 0 moves to bit 31: 1 becomes 2³¹ = 2147483648.

Example 2
Input:  n = 6
Output: 1610612736

6 is 110 in binary. Its bits 1 and 2 become bits 30 and 29: 2³⁰ + 2²⁹ = 1610612736.

Constraints

  • 0 ≤ n ≤ 4294967295
  • n is a whole number.

Stuck?

Hint 1

Take the bits of n from the lowest up, and push each onto the result from the right, 32 times in all.

Hint 2

Each step: shift the result left by one, add n & 1 with |, and shift n right with >>>. The last shift can set the sign bit, so finish with >>> 0.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur