Reverse Bits
Problem
Given a 32-bit unsigned integer n, reverse the bits of the binary representation of n and return the result.
Examples
Example 1:
Input: n = 00000000000000000000000000010101
Output: 2818572288 (10101000000000000000000000000000)
Explanation: Reversing 00000000000000000000000000010101, which represents the unsigned integer 21, gives us 10101000000000000000000000000000 which represents the unsigned integer 2818572288.
Constraints
You should aim for a solution with O(1) time and O(1) space.
Solution
Shift result left and insert the LSB of n, then shift n right.
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
decltype(n) result = 0;
for (int i = 0; i < 32; ++i) {
result = (result << 1) | (n & 1);
n = n >> 1;
}
return result;
}
};