Reverse Bits
Try solving the Reverse Bits problem.
Statement
Given an unsigned 32-bit integer n
, we need to calculate a 32-bit unsigned integer with reversed bits. When we say “reverse” we don’t mean flipping the s to s and vice versa, but simply reversing the order in which they appear, i.e., from left-to-right to right-to-left.
Constraints:
- The input must be a binary string of length
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Reverse Bits
What is the output if we have 5 as an unsigned 32-bit integer and reverse the bits?
4294967290
2684354560
5
2684354560
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.
Try it yourself
Implement your solution in the following coding playground.
We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(1) time and takes O(1) space. You may try to translate the logic of the solved puzzle into a coded solution.
package mainfunc reverseBits(n uint32) uint32 {// Replace this placeholder return statement with your codereturn 0}