Pairing exchange. Write a program to exchange the odd and even bits of an integer, using as few instructions as possible (that is, bit 0 and bit 1, bit 2 and bit 3, and so on).
Example 1:
- Input: num = 2 (or 0b10)
- Output 1 (or 0b01)
Example 2:
- Input: num = 3
- Output: 3
Sample code:
class Solution(object):
def exchangeBits(self, num):
"""
:type num: int
:rtype: int
"""
# return ((num & 0xaaaaaaaa) >> 1) ^ ((num & 0x55555555) << 1)
# 与上面代码写的效果是一样的
return ((num & 0xaaaaaaaa) >> 1) | ((num & 0x55555555) << 1)
a = Solution()
b = a.exchangeBits(3)
print(b)
running result:
Problem-solving ideas
Regarding binary and bit operations: Take out the number at a specific position.
The odd-numbered bits can be manipulated first, and then the even-numbered bits can be manipulated.
- For odd-numbered bits, use 101010 (ie 0xAA) as a mask, extract the odd-numbered bits, and shift them one bit to the right;
- For even-numbered bits, use 010101 (that is, 0x55) as a mask, extract the even-numbered bits, and shift them one bit to the left.
step:
- Take out the even digits and shift to the right by 1
- Take out the odd-digit number and shift it to the left by 1
- Sum or bitwise exclusive or