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

思路
思路一:转换成二进制字符串,然后反转字符串
class Solution:
def reverseBits(self, n: int) -> int:
ans = bin(n)[2:][::-1]
if len(ans) < 32:
ans += '0' * (32 - len(ans))
return int(ans, 2)
思路二:逐位操作
- n&1可以检索最右边的位是0还是1,也可以判断奇数还是偶数;
- n = n >> 1右移一位
- n = n << 1左移一位- class Solution:
- def reverseBits(self, n: int) -> int:
- ans = 0
- power = 31
- while n != 0:
- ans += (n & 1) << power
- n = n >> 1
- power -= 1
- return ans
 
更多解法
https://leetcode-cn.com/problems/reverse-bits/solution/dian-dao-er-jin-zhi-wei-by-leetcode/
 
                         
                                

