小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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?

Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

分析

题目要求将一个32位无符号整数对应的二进制串反转,求翻转后的二进制串对应的新的32位无符号整数值。

也就是说,只要我们求得该输入无符号整数的二进制表示形式,将其反转,再转换为十进制即可。

注意的问题,题目明确要求了32位,也就是说对于整数的二进制串必然长度为32,若长度不足则用0补齐。处理后再反转,求新的十进制。

另外,对于此题,我们还需要想到用位运算处理来提高运算速度。

AC代码


class Solution {
public:
    //方法一
    uint32_t reverseBits(uint32_t n) {
        vector<int> bits;
        //利用位运算求二进制序列
        while (n)
        {
            bits.push_back(n & 1);
            n = n>> 1;
        }

        //求二进制位反转后对应的十进制数,若bits中长度不足32,以0步之
        uint32_t ret = 0;
        int size = bits.size();
        for (int i = 0 ; i <size; ++i)
        {
            ret = ret + bits[i] * (1 << (32 - i - 1));
        }//for
        return ret;

    }

    //简洁的解法2
    uint32_t reverseBits2(uint32_t n) {
         uint32_t res = 0;
         for (int i = 0; i < 32; ++i) {
             res |= (((n >> i) & 1) << (31 - i));

        }
         return res;
    }
};

GitHub测试程序源码

posted on 2015-11-02 20:54  Coding菌  阅读(489)  评论(0编辑  收藏  举报