Search⌘ K
AI Features

Reverse Bits

Explore how to reverse the bit order of a 32-bit unsigned integer without altering bit values. Understand the problem constraints, learn bitwise operations for reversing bits, and apply this knowledge to implement an optimized O(1) time and space solution, enhancing your problem-solving skills in bitwise manipulation.

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 00s to 11s 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 22's complement notation for representing signed integers.

Constraints:

  • The input must be a binary string of length 3232

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

1.

What is the output if we have 5 as an unsigned 32-bit integer and reverse the bits?

A.

4294967290

B.

2684354560

C.

- 5

D.

- 2684354560


1 / 2

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.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

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.

Java
usercode > Solution.java
import java.util.*;
public class Solution{
// Treat n as an unsigned value
public static int reverseBits(int n) {
// Replace this placeholder return statement with your code
return 0;
}
}
Reverse Bits