[Bit Operations-Simple] Interview Questions 05.07. Pairing Exchange

[Title]
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
[Note]
range in a num [0, 2 30 - 1] between, not An integer overflow will occur.
[Code]
[Python]
Insert picture description here

class Solution:
    def exchangeBits(self, num: int) -> int:
        s_num=list(bin(num)[2:])
        if len(s_num)%2:
            s_num.insert(0,"0")
        i=1
        while i < len(s_num):
            temp=s_num[i]
            s_num[i]=s_num[i-1]
            s_num[i-1]=temp
            i+=2
        return int("".join(s_num),2)

[Method 2: Bit operation]
Insert picture description here

class Solution:
    def exchangeBits(self, num: int) -> int:
        odd = num & 0x55555555
        even = num & 0xaaaaaaaa
        odd <<=1
        even >>=1
        return odd | even

Guess you like

Origin blog.csdn.net/kz_java/article/details/115092536