码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_num190_Reverse Bits

时间:2015-03-08 18:53:49      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

标签:leetcode

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!