Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string `00000010100101000001111010011100` is represented as the unsigned integer `43261596`, so the function should return `964176192`, which is the binary representation of `00111001011110000010100101000000`.
Example 2:
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string `11111111111111111111111111111101` is represented as the unsigned integer `4294967293`, so the function should return `3221225471`, which is the binary representation of `10111111111111111111111111111111`.
Note:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
// Extract the least significant bit of n
int bit = n & 1;
// Left shift the result to make space for the new bit
result <<= 1;
// Add the bit to the result
result |= bit;
// Right shift n to process the next bit
n >>= 1;
}
return result;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?