190. Reverse Bits
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Bit Manipulation
- Time
- O(1)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven a 32-bit unsigned integer, return a new integer whose bits are the original's bits in reversed order (bit 0 becomes bit 31, bit 1 becomes bit 30, and so on).
Approach
- Iterate over all 32 bit positions, extracting the lowest bit of
neach iteration vian & 1, then right-shiftingnby 1. - Place that extracted bit into the mirror position of the result by OR-ing
reswith the bit shifted left to position(31 - i). - Because the bit width is fixed at 32, this always runs exactly 32 iterations — truly O(1) work with O(1) space.
- Using
uint32_t(unsigned) throughout avoids undefined behavior from left-shifting into the sign bit.
#include <cstdint>
using namespace std;
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
for (int i = 0; i < 32; ++i) {
// Place the lowest bit of n into mirror position (31-i) of res
res |= (n & 1u) << (31 - i);
n >>= 1;
}
return res;
}
}; Time O(1) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int reverseBits(int n) {
int res=0;
for(int i=0; i<32; ++i){
if(n==0){
break;
}
if(n&1){
res+=(1<<(31-i));
}
n>>=1;
}
return res;
}
};
// Time Complexity: O(1)
// Space Complexity: O(1) Time O(1) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.