We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy bit manipulation problem, graded against 6 test cases (3 of them hidden).
XOR, masks, and shifts - constant-space tricks for counting and pairing.
Reach for it when you see: "Appears once/twice", powers of two, or an explicit O(1) space requirement.
More Bit Manipulationproblems →The algorithm mirrors reversing a string: pull bits off the bottom of the input and push them onto the bottom of the output, which shifts previously-placed bits up toward the top.
Each round does three things - shift the result left one position, OR in the input's lowest bit (`n & 1`), then shift the input right one position.
The critical constraint is the fixed 32 iterations. Stopping when the input reaches zero seems like a natural optimization and produces the wrong answer, because the remaining leading zeros still need shifting into place. Reversing `1` must yield `2147483648`: 31 zeros trail the single set bit.
JavaScript needs care because bitwise operators coerce to signed 32-bit, so a result with the top bit set reads as negative. The final `>>> 0` reinterprets it as unsigned. Python has unbounded integers, so the 32-bit width has to be imposed by the loop rather than by the type.
If asked to optimize for many calls, the two standard answers are memoizing byte-sized chunks in a 256-entry lookup table, or the branchless divide-and-conquer swap of adjacent bits, then pairs, then nibbles, bytes, and halves - O(log 32) operations with no loop.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.