Reversing Bits of an Integer
The "Reverse Bits" problem is a classic bit manipulation challenge that involves reversing the bits of a given 32-bit unsigned integer.
Problem Statement
Given a 32-bit unsigned integer n, the goal is to reverse its bits and return the result.
Example
- Input:
n = 43261596(binary representation:00000010100101000001111010011100) - Output:
964176192(binary representation:00111001011110000010100101000000)
JavaScript Solution
Here's an efficient way to solve this problem in JavaScript:
function reverseBits(n) {
let result = 0;
for (let i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>>= 1;
}
return result >>> 0; // Ensure unsigned 32-bit integer
}
Breaking Down the Solution
-
Initialization: Start with
resultset to 0. This variable will hold the reversed bits. -
Iterative Bitwise Operations: For 32 iterations (each iteration represents a bit in the 32-bit integer):
-
Left-shift
result: Shiftresultleft by one bit (result << 1). This operation makes space for adding the new bit at the least significant position. -
Add Bit to
result: Use bitwise OR (|) to add the rightmost bit ofntoresult. The expressionn & 1isolates the least significant bit ofn, which is then added toresult. -
Right-shift
n: Shiftnright by one bit (n >>>= 1). This operation moves all bits ofnto the right by one position, bringing the next bit in line to be processed.
-
-
Return Unsigned Integer: The expression
result >>> 0convertsresultto an unsigned 32-bit integer. This step ensures that the final returned value is in the correct format, respecting the constraints of the problem.
Conclusion
Reversing the bits of an integer is a valuable exercise in bit manipulation. It demonstrates how bitwise operations can be used to precisely control and manipulate individual bits within integers. This problem is not only frequently asked in technical interviews but also plays a crucial role in areas like low-level computing and digital signal processing, where bit-level manipulation is common.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.