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 0s to 1s and vice versa, but simply reversing the order in which they appear, i.e., from left-to-right to right-to-left.
Constraints:
- 0≤
n
≤232
Solution
We start by initializing a variable result
to 0, which will hold the 32-bit unsigned integer obtained by reversing the bits of the input integer n
. We start from the rightmost bit (i.e., the least significant bit) of n
, iterate through each bit, and reverse it. In each iteration, we left shift the result
by 1 position, effectively making room for the next bit to be added, and then extract the rightmost bit from n
using a bitwise AND (&
) operation with 1. This operation sets all bits of n
to 0 except for the rightmost bit, which is either 0 or 1.
After extracting the rightmost bit, we OR (|
) it with the result
to effectively add the extracted bit to the reversed result
. We now right shift the original number n
by 1 position, effectively removing the already processed rightmost bit.
We continue the process until all bits in n
have been reversed and are saved in the result
. Now, return the result
variable.
Now, let’s look at the following illustration to get a better understanding of the solution: