LeetCode 190 Reverse Bits

首先最直观的暴力做法:

 1 uint32_t reverseBits(uint32_t n) {
 2         string str(32,'0');
 3         int index = 31;
 4         do{
 5             str[index--] = n%2+'0';
 6             n/=2;
 7         }while(n);
 8         uint32_t result = 0;
 9         for(int i=31; i>=0;--i){
10             result = result*2 + (str[i]-'0');
11         }
12         return result;      
13 }

 

然后思考怎么通过位操作来实现reverse,直观理解就是最低bit位变成了最高bit位,但是如何通过为操作进行调整呢?

1.高16位和低16位进行交换

2.高16位的高8位与低8位进行交换,低16位的高8位与低8位进行交换

。。。

最后,每两位进行交换就可以实现

例如8位bit数, abcdefgh

高四位与第四位交换 => efghabcd

2=> ghefcdab

1=> hgfedcba

1 uint32_t reverseBits(uint32_t n){
2         n = (n>>16) | (n<<16);
3         n = ((n&0xff00ff00)>>8) | ((n&0x00ff00ff)<<8);
4         n = ((n&0xf0f0f0f0)>>4) | ((n&0x0f0f0f0f)<<4);
5         n = ((n&0xcccccccc)>>2) | ((n&0x33333333)<<2);
6         n = ((n&0xaaaaaaaa)>>1) | ((n&0x55555555)<<1);
7         return n;
8     }

 

posted @ 2015-12-03 16:25  Acker  阅读(246)  评论(0编辑  收藏  举报