[LeetCode]Reverse Bits

题目描述:

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

题目大意:

按位反转一个给定的32位无符号整数。

例如,输入整数43261596(二进制形式为:00000010100101000001111010011100),返回964176192(转换为二进制为00111001011110000010100101000000)。

进一步思考:

如果函数需要被调用很多次,怎样优化?

解题思路:

位操作(bit manipulation)

Python代码(朴素解法):

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

优化方案:

参考:https://oj.leetcode.com/discuss/27338/8ms-c-code-some-ideas-about-optimization-spoiler

以4位为单位执行反转,将0x0至0xF的反转结果预存在一个长度为16的数组中,反转时直接查询即可。

C代码:

char tb[16] = {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};

uint32_t reverseBits(uint32_t n) {
        int curr = 0;
        uint32_t ret = 0;
        uint32_t msk = 0xF;
        for(int i = 0; i < 8; i++) {
            ret = ret << 4;
            curr = msk&n;
            ret |= tb[curr];
            n = n >> 4;
        }
        return ret;
}

 

本文链接:http://bookshadow.com/weblog/2015/03/08/leetcode-reverse-bits/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论