颠倒二进制位
概述:颠倒给定的 32 位无符号整数的二进制位。
输入:n = 00000010100101000001111010011100
输出:964176192 (00111001011110000010100101000000)
输入:n = 11111111111111111111111111111101
输出:3221225471 (10111111111111111111111111111111)
方法一:循环
思路:这是最容易想到的方法了,每次把 ans 左移,把 n 的二进制末尾数字,拼接到结果 ans 的末尾。然后把 n 右移。
# 循环
class Solution:
def reverseBits(self, n: int) -> int:
ans = 0
for i in range(32):
ans = (ans << 1) | (n & 1)
n >>= 1
return ans
方法二:分治
思路:数字分为两半,然后交换这两半的顺序;然后把前后两个半段都再分成两半,交换内部顺序……直至最后交换顺序的时候,交换的数字只有 1 位。
# 分治
class Solution:
def reverseBits(self, n: int) -> int:
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
总结
分治太骚了吧。。。