190. 颠倒二进制位
题目:颠倒给定的 32 位无符号整数的二进制位。
链接 https://leetcode.cn/problems/reverse-bits/
个人思路
- 先将输入整数转换为二进制,注意题目要求的是32位,所以不足32位的要进行补0操作,然后利用列表进行翻转再重新连接起来,重新转换为10进制即可
class Solution:
def reverseBits(self, n: int) -> int:
s = bin(n)[2:] # 转换为二进制后得到字符串开头为ob
s1 = '0'*(32-len(s))+s # 不足32位的以0补足
temp = list(s1)
temp.reverse()
s2 = ''.join(temp)
return int(s2,2) # 转换为十进制
其他思路
- 逐位颠倒
每次把 res 左移,把 n 的二进制末尾数字,拼接到结果 res 的末尾。然后把 n 右移。
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
res = 0
for i in range(32):
res = (res << 1) | (n & 1)
n >>= 1
return res
时间复杂度:O(1)
空间复杂度:O(1)
- 位运算分治
把数字分为两半,然后交换这两半的顺序;然后把前后两个半段都再分成两半,交换内部顺序……直至最后交换顺序的时候,交换的数字只有 1 位。
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
n = (n >> 16) | (n << 16);
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
return n;
时间复杂度:O(1)
空间复杂度:O(1)
参考:
作者:fuxuemingzhu
链接:https://leetcode.cn/problems/reverse-bits/solution/fu-xue-ming-zhu-xun-huan-yu-fen-zhi-jie-hoakf/