bit manipulation

Leetcode 190. Reverse Bits : https://leetcode.com/problems/reverse-bits/

1
2
3
4
5
6
7
8
9
10
11
12
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
int i = 0;
while(i++ < 32){

res += n & 1;
n >>= 1;
if(i < 32)
res <<= 1;
}
return res;
}

Tips

  1. Get the bit at the lowest position of a number n => n & 1 .
  2. add to the end of the new number, new number should left shift 1, and the original number should right shift 1.