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<性質:0異或x=x (x=0,1)
If this function is called many times, how would you optimize it?
建立所有情況的對照表,直接根據表對應讀出