LeetCode算法题190:颠倒二进制解析

颠倒给定的 32 位无符号整数的二进制位。
示例:

输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
     返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。

进阶:
如果多次调用这个函数,你将如何优化你的算法?

这个题第一个想法就是逐位判断1或0然后添加到新数中,那就产生了简单的想法,首先判断原数的低位,如果为1,那么就对新数加1然后左移,如果为0,那么新数直接左移,然后原数右移,但是这样最后会多移一步,所以需要简单处理。python程序如下:
python3源代码:

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        result = 0
        for i in range(32):
            result = (result << 1) + (n & 1)
            n = n >> 1
        return result

有一种更厉害的解法,其原理如下解释:
abcdefgh -> efghabcd -> ghefcdab -> hgfedcba
所以8位只需要交换3次,其运算复杂度是O(logn)。
C++源代码:

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;
    }
};

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/83931935