首页 > 其他 > 详细

LeetCode 【190. Reverse Bits】

时间:2016-08-06 17:18:46      阅读:189      评论:0      收藏:0      [点我收藏+]

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

 

思路

基本思路即分别提取出当前最高位和最低位的信息,进行交换即可,然后最高位--,最低位++,直到相遇;32位数,所以0-15和16-31分别进行操作。这边我先判断最高位,如果为1,则判断最低为,如果也为1,不进行操作,如果为0,则最低为变成1,这边用到了位移,然后最高位做减法,则变为0。如果最高位为0,则同理,做相反的操作即可。

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        int cur;
        for(int i = 31 ; i >= 16;i--){
            if(n&(1<<i)){
                cur = n&1<<(31-i);
                if(cur == 0){
                n -= 1<<i;
                n += 1<<(31-i);
                }
                
            }
            else{
                cur = n&1<<(31-i);
                if(cur != 0){
                n += 1<<i;
                n -=1<<(31-i);
                }
            }
        }
        return n;
    }
};

  

LeetCode 【190. Reverse Bits】

原文:http://www.cnblogs.com/rockwall/p/5744435.html

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