03_颠倒二进制位

2019-11-06  本文已影响0人  butters001
class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        n = bin(n)[2:]
        # 因为是32位 所以长度不够要在前面补0
        for i in range(32-len(n)):
            n = '0' + n
        reverse = n[::-1]
        return int('0b' + reverse, 2)


# leetcode 最优解
class Solution2:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        r = 0
        for i in range(32):
            tmp = ((n >> 1) << 1) ^ n
            if tmp == 1:
                r = (r << 1) + 1
            else:
                r = r << 1
            n = n >> 1
        return r

上一篇下一篇

猜你喜欢

热点阅读