
Problem Statement
The task is to reverse the bits of a given 32-bit unsigned integer represented as a binary string. This involves flipping the order of bits from left to right such that the first bit becomes the last one, the second bit becomes the one before the last, and so on, until the last bit becomes the first. This bitwise operation changes the position of all bits in the binary representation of the number while keeping the binary structure intact.
While some programming languages don't support unsigned integers directly (like Java), and use signed types instead, this does not change the binary representation of numbers in our context. The reverse process applies universally to the bit structure, whether the integer is signed or unsigned. The goal is to return the new integer formed by the reversed bits in decimal form accompanied by its new binary representation.
Examples
Example 1
Input:
n = 00000010100101000001111010011100
Output:
964176192 (00111001011110000010100101000000)
Explanation:
The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2
Input:
n = 11111111111111111111111111111101
Output:
3221225471 (10111111111111111111111111111111)
Explanation:
The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Constraints
- The input must be a binary string of length
32
Approach and Intuition
To solve this problem, we can employ a straightforward bit manipulation approach. Here’s a step-by-step breakdown of how our solution would work, taking into consideration the constraints and examples provided:
Initialize an empty 32-bit integer for the result where all bits are set to
0
. This will store the reversed bits.Iterate 32 times since the input is a 32-bit integer:
For each iteration, shift the result to the left by one bit to make room for the next bit to be reversed.
Extract the right-most bit from the input using a bitwise AND with
1
(which would be input& 1
).Increment the extracted bit to the right-most side of the ongoing result. This can be done using a bitwise OR between the shifted result and the extracted bit.
Shift the input right by one to process the next bit during the subsequent iteration.
Following the completion of iterations, the result now holds the binary integer that is the reverse of the original input.
This approach moves sequentially through each bit of the input and appropriately adjusts the bits in the result to their reversed positions, ensuring that by the end, the bits are completely reversed respecting their original ordering.
This technique leverages basic bit manipulation operations, such as bitwise AND, OR, and shift operations, which are efficient and commonly supported across different programming languages. The overall time and space complexity of the approach is constant, (O(1)), as it deals with a fixed-size input and uses a bounded number of operations.
Solutions
- C++
- Java
- Python
class Solution {
public:
uint32_t reverseBits(uint32_t value) {
value = (value >> 16) | (value << 16);
value = ((value & 0xff00ff00) >> 8) | ((value & 0x00ff00ff) << 8);
value = ((value & 0xf0f0f0f0) >> 4) | ((value & 0x0f0f0f0f) << 4);
value = ((value & 0xcccccccc) >> 2) | ((value & 0x33333333) << 2);
value = ((value & 0xaaaaaaaa) >> 1) | ((value & 0x55555555) << 1);
return value;
}
};
This article provides a concise guide to reversing the bits of a 32-bit unsigned integer in C++. The provided C++ function utilizes bitwise operations to achieve this task efficiently. Let’s break down how the code operates:
- In the first line of the function, the code swaps the higher and lower 16 bits using bit shifting and bitwise OR operation.
- Subsequent lines perform further bit-level reversals. Each operation targets increasingly smaller segments—first 8-bit chunks, then 4 bits, 2 bits, and finally 1 bit—employing bitwise masks and shifts.
- Masks such as
0xff00ff00
and0x00ff00ff
allow for selective targeting of byte segments, and similar masks are applied for smaller bit segments. - Each step reduces the level of granularity until each individual bit is reversed in the final operation using masks
0xaaaaaaaa
and0x55555555
.
The resulting function efficiently reverses the bits of the input value, returning the newly arranged 32-bit unsigned integer. This solution offers not only efficacy in terms of execution but also clarity, using a series of logical bit manipulations.
public class Solution {
public int flipBits(int m) {
m = (m >>> 16) | (m << 16);
m = ((m & 0xff00ff00) >>> 8) | ((m & 0x00ff00ff) << 8);
m = ((m & 0xf0f0f0f0) >>> 4) | ((m & 0x0f0f0f0f) << 4);
m = ((m & 0xcccccccc) >>> 2) | ((m & 0x33333333) << 2);
m = ((m & 0xaaaaaaaa) >>> 1) | ((m & 0x55555555) << 1);
return m;
}
}
The "Reverse Bits" solution provided involves a series of bitwise operations in Java to reverse the bits of an integer. Below is a concise summary of how the solution works:
- Declare a method
flipBits
that receivesm
as an integer argument. - The first operation shifts the bits of
m
to reverse the order of bytes, treating the integer as composed of two-byte halves. - Subsequent lines process progressively smaller groups of bits:
- Separates and reverses bytes using masks
0xff00ff00
and0x00ff00ff
. - Handles nibbles (4 bits) with masks
0xf0f0f0f0
and0x0f0f0f0f
. - Interchanges pairs of bits using masks
0xcccccccc
and0x33333333
. - Finally, swaps individual bits using masks
0xaaaaaaaa
and0x55555555
.
- Separates and reverses bytes using masks
- Each step involves a mask and shift operation:
- Apply a bit mask to isolate groups of bits.
- Shift isolated bits to their new reversed positions.
- The final line returns the reversed bit integer.
This method efficiently reverses the bits of an integer using a combination of masks and shifts, ensuring the process is both clear and optimal in terms of performance.
class Solution:
def reverse32(self, x: int) -> int:
x = (x >> 16) | (x << 16)
x = ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8)
x = ((x & 0xF0F0F0F0) >> 4) | ((x & 0x0F0F0F0F) << 4)
x = ((x & 0xCCCCCCCC) >> 2) | ((x & 0x33333333) << 2)
x = ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1)
return x
The solution employs a bit manipulation technique to reverse the bits of a 32-bit integer in Python. To accomplish this, the provided code performs the following operations:
Swap the Halfwords: The code first swaps the two halves (16 bits each) of the 32-bit integer. This is achieved using:
x = (x >> 16) | (x << 16)
Swap the Bytes: It then swaps consecutive 8-bit blocks by masking and shifting bits.
x = ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8)
Swap the Nibbles: Each byte (now correctly positioned) is split into nibbles (4 bits) and swapped.
x = ((x & 0xF0F0F0F0) >> 4) | ((x & 0x0F0F0F0F) << 4)
Swap Pairs of Bits: Consecutive groups of two bits are swapped next.
x = ((x & 0xCCCCCCCC) >> 2) | ((x & 0x33333333) << 2)
Swap Individual Bits: Finally, each adjacent pair of bits gets swapped.
x = ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1)
By the end of these operations, x
holds the value of the original integer with all bits reversed, and this value is returned. This method ensures that every bit in the integer occupies the position that its mirror image would in a purely reversed binary number, thus effectively reversing the bits of the integer.
No comments yet.