首页 > 其他 > 详细

leetcode_num190_Reverse Bits

时间:2015-03-08 18:51:21      阅读:199      评论:0      收藏:0      [点我收藏+]

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?

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

leetcode_num190_Reverse Bits

原文:http://blog.csdn.net/eliza1130/article/details/44134537

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!