[leetcode190]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

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

算法:

先计算出n的二进制表示,由于涉及到2的0-31次幂,所以使用列表表示n的二进制,其index与位数正好对应,两次扫描解决。
rest = n
第一次从index=31处开始,逐次得到每个位置的值,array[index] = rest/2**index,
rest -= array[index]*2**index。
第二次从index=0处开始,累加每个位置的值array[index]*2**(31-index).
最后累加和就是结果。

代码:

class Solution(object):
    def reverseBits(self, n):
        """ :type n: int :rtype: int """
        array = [0 for _ in range(32)]
        rest = n
        for index in range(31,-1,-1):
            array[index] = rest/2**index
            rest -= array[index]*2**index

        s = 0
        for idx, value in enumerate(array):
            s += value*2**(31-idx)
        return s
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务