Reverse Bits
Explore how to reverse the bits of a 32-bit unsigned integer by rearranging their order from left to right. This lesson helps you understand bitwise operations and implement a constant-time, constant-space solution useful for optimizing coding interview problems involving binary manipulation.
We'll cover the following...
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.
Note: In certain programming languages, such as Java, we do not have an unsigned integer type. Therefore, both input and output values are provided as signed integers. This should not impact our implementation because the internal binary representation of integers remains the same, whether they are signed or unsigned. In Java, the compiler utilizes the s complement notation for representing signed integers.
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.
import java.util.*;public class Solution{// Treat n as an unsigned valuepublic static int reverseBits(int n) {// Replace this placeholder return statement with your codereturn 0;}}