LeetCode 190: Reverse Bits
Problem Description
Explanation:
To reverse the bits of a 32-bit unsigned integer, we can iterate through each bit of the input integer from right to left (LSB to MSB) and construct the reversed integer by shifting the bits to the left and appending the current bit.
- Initialize a variable
result
to store the reversed bits. - Iterate through each bit of the input integer from right to left.
- Check if the current bit is 1, then set the corresponding bit in the result by ORing with 1 shifted by the remaining iterations.
- Finally, return the result as the reversed integer.
Time Complexity: O(1) - Since we are iterating through a fixed number of bits (32 bits). Space Complexity: O(1) - Constant space is used. :
Solutions
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>= 1;
}
return result;
}
Related LeetCode Problems
Loading editor...