leetcode之Reverse Bits(190)

题目:

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

示例:

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

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

python代码:

class Solution:
    def reverseBits(self, n):
        nums, res = [], 0
        while n >= 1:
            nums.append(n % 2)
            n = n // 2
        while len(nums) < 32:
            nums.append(0)
        for i,j in enumerate(nums[::-1]):
            res += j * 2** i
        return res

猜你喜欢

转载自blog.csdn.net/cuicheng01/article/details/82534928