Reverse bits of a given 32 bits unsigned integer.
归并法
class Solution { public: uint32_t reverseBits(uint32_t n) { n=(n>>16)|(n<<16); n=((n&0xff00ff00)>>8)|((n&0x00ff00ff)<<8); n=((n&0xf0f0f0f0)>>4)|((n&0x0f0f0f0f)<<4); n=((n&0xcccccccc)>>2)|((n&0x33333333)<<2); n=((n&0xaaaaaaaa)>>1)|((n&0x55555555)<<1); return n; } };
>> << 移动补零
交替数字法:
class Solution { public: uint32_t exchange(int i,int j,uint32_t m){ int lo=(m>>i)&1; int hi=(m>>j)&1; if (lo!=hi){ m^=((1<<i)|(1<<j)); } return m; } uint32_t reverseBits(uint32_t n) { int L=32; for(int i=0;i<L/2;i++){ n=exchange(i,L-1-i,n); } return n; } };性质:0异或x=x (x=0,1)
If this
function is called many times, how would you optimize it?
建立所有情况的对照表,直接根据表对应读出
原文:http://blog.csdn.net/eliza1130/article/details/44134537