leetcode_num190_Reverse Bits

2015-07-20 17:11:44 来源: 作者: 浏览: 3

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?

建立所有情况的对照表,直接根据表对应读出

-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: