# Clean short C++ solution, maybe you like it

• ``````class Solution {
public:
uint32_t reverseBits(uint32_t n) {
auto r = 0;
for (auto i = 0; i < 32; ++i) {
r <<= 1;
r |= n & 1;
n >>= 1;
}
return r;
}
};``````

• why do we need r >> 1 at the last line?

• Cause `r` is the next bit to fit `n & 1`, that's why `r`'s type is `uint64_t`. Read `for loop` carefully, and you will figure it out.

• ``````uint32_t reverseBits(uint32_t n) {
uint32_t ret=0;
for(int i=0; i<32; i++) {
ret<<=1;
if(n&1) {
ret|=1;
}
n>>=1;
}
return ret;
}
``````

Maybe better?

• Surely you can write it like that, but `if` is unnecessary cause shorter and faster `ret |= n & 1` equals to that. Thanks anyway for reminding me. I will edit the code in case of someone being confused.

``````uint32_t reverseBits(uint32_t n) {
auto r = 0;
for (auto i = 0; i < 32; ++i) {
r <<= 1;
r |= n & 1;
n >>= 1;
}
return r;
}``````

• Easier to understand, thanks for sharing.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.