配对交换。编写程序,交换某个整数的奇数位和偶数位,尽量使用较少的指令(也就是说,位0与位1交换,位2与位3交换,以此类推)。
示例1:
输入:num = 2(或者0b10)
输出: 1 (或者 0b01)
示例2:
输入:num = 3
输出:3
提示:
- num的范围在[0, 2^30 – 1]之间,不会发生整数溢出。
Python 解答:
1.常规思路
class Solution:
def exchangeBits(self, num: int) -> int:
def transform(n):
res = [0 for i in range(32)]
i = 0
while n > 0:
r = n&1
res[i] = r
n >>= 1
i += 1
return res
def retransform(arr):
pre = 0
for item in arr:
pre <<= 1
pre += item
return pre
arr = transform(num)
if len(arr) == 1:
return arr[0]
for i in range(0, len(arr), 2):
arr[i], arr[i+1] = arr[i+1], arr[i]
return retransform(arr[::-1])
2.小技巧
class Solution:
def exchangeBits(self, num: int) -> int:
odd = (num & 0x55555555) << 1
even = (num & 0xaaaaaaaa) >> 1
return odd | even
留言