📝 Problem Details
- Title:
190. Reverse Bits
- Link: https://leetcode.com/problems/reverse-bits/
- Difficulty: Easy
- Tags/Categories: Bit-Manipulation
reverse bits of a given 32 bits unsigned integer
💡 Explanation of Solution
- initialize result as 0
- for each of the 32 bits
- shift the result to the left by 1 to make room for the next bit
- take the last bit of n(n&1) and add it to the result
- then shift n to the right by 1 to move to the next bit
⌛ Complexity Analysis
Time Complexity: O(32) ~ O(1)
Space Complexity: O(1)
💻 Implementation of Solution
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
for (int i = 0; i < 32; i++) {
result <<= 1; // Make space for the next bit
result |= (n & 1); // Add the last bit of n
n >>= 1; // Drop the last bit from n
}
return result;
}
};