Reverse Bits

Easy#190bit by bit

You get an unsigned integer of a fixed width — 32 bits on LeetCode. Write its bits in the opposite order, the lowest first, and return the number they make; the zeros at the top count too. To draw every bit, our example has 8 bits: n = 22 = 00010110 — the answer is 01101000 = 104.

input
n: an even non-negative integer, taken as 32 bits.
returns
The number whose 32 bits are those of n in reverse order: bit 0 of n becomes bit 31, bit 1 becomes bit 30, and so on. 2 (bit 1) gives 1073741824 (bit 30).
constraints
  • 0 ≤ n ≤ 2³¹ − 2
  • n is even
our 16 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} n
 * @return {number}
 */
function reverseBits(n) {

}
Ctrl ↵
format
reset

saved in this browser

16 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more bit manipulation problems

Pattern “Bit manipulation” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.