Upside-Down Light Strip

Easybit manipulationAlso known as Reverse Bits

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

The installer mounted the strip the wrong way round, so every pattern now shows mirrored. Rewiring is not an option. Instead, the controller should mirror each number before sending it, so the window looks the way the designer meant.

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: bit 0. Mirrored, 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 the string, and parse it back. That works and runs in O(32), which is fine.

The trap is the padding. Forget it and 1 mirrors to 1 instead of 2,147,483,648. The string version also hides what is really happening. Doing it with shifts teaches you how to move bits around 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