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:
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.
Rust Solution
u32 is unsigned, so >> is already a logical (zero-filling) shift and the returned value is naturally an unsigned 32-bit integer — none of JavaScript's >>> 0 normalisation is needed. Rust function parameters are immutable, so let mut n = n shadows n with a mutable binding before the loop mutates it via n >>= 1. The for _ in 0..32 range binds the counter to _ because only the iteration count matters, and the bare trailing result expression returns the value without a return keyword.
Go Solution
uint32 is an unsigned type, so >> zero-fills and result stays a valid unsigned 32-bit value with no >>> 0 unsigning step. Unlike Rust, the parameter n uint32 is directly mutable, so n >>= 1 reassigns it in place with no rebinding. The C-style three-clause header for i := 0; i < 32; i++ drives the 32 passes even though i is unused, and return result hands the value back explicitly.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.