LeetCode 190 Reverse Bits (Python)

Posted by 小明MaxMing on July 12, 2020

题目

Reverse bits of a given 32 bits unsigned integer.

解题思路

  1. 每次取这个数的最后一位,然后将其左移到对应的位置,加到结果里
  2. 转换成二进制字符串,然后翻转

代码

class Solution:
    def reverseBits(self, n: int) -> int:
        res, power = 0, 31
        while n:
            res += (n & 1) << power
            n >>= 1
            power -= 1
        return res
class Solution:
    def reverseBits(self, n: int) -> int:
        return int(bin(n)[2:].zfill(32)[::-1], 2)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅