Upside-Down Light Strip

Easybit manipulationAlso known as Reverse Bits

A shop window has a strip of 32 lights controlled by one 32-bit number. Bit 0 (the lowest) switches the leftmost light, bit 1 the next, and so on up to bit 31 on the far right. The designer stores patterns as these numbers.

The installer mounted the strip the wrong way round, so every pattern shows mirrored. Instead of rewiring, the controller should mirror each number before sending it.

Your task

Write mirrorPattern(pattern). Treat pattern as exactly 32 bits, including leading zeros. Return the number you get by reversing the order of those 32 bits: bit 0 moves to bit 31, bit 1 to bit 30, and so on.

Both the input and the result are unsigned: whole numbers from 0 to 4,294,967,295. Never return a negative number.

mirrorPattern(pattern: int) → int

Examples

Example 1
Input
pattern = 1
Output
2147483648
Why

Only the leftmost light is on, which is bit 0. After mirroring, only bit 31 is on, which is 2³¹ = 2,147,483,648. Reversing the short string "1" would give 1, which is wrong: the 31 leading zeros count too.

Example 2
Input
pattern = 6
Output
1610612736
Why

6 is ...00110: bits 1 and 2 are on. They move to bits 30 and 29, so the answer is 2³⁰ + 2²⁹ = 1,610,612,736.

Example 3
Input
pattern = 4294967295
Output
4294967295
Why

All 32 lights are on. A mirror of a full strip is still a full strip.

Constraints

  • 0 ≤ pattern ≤ 4,294,967,295 (that is, 2³² - 1)
Start with brute force

Convert the number to a binary string, pad it with zeros to 32 characters, reverse it, and parse it back. That works, in O(32).

The trap is the padding: forget it and 1 mirrors to 1 instead of 2,147,483,648. Shifts are worth learning here because they move bits directly, which you need whenever you pack data into integers.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code