Skip to main content

Command Palette

Search for a command to run...

二進位奇偶位互換

Updated

問題

給定一個非負整數,將其二進位表示中的奇偶位元互換。

範例說明

以數字 23 為例:

1. 23 的二進位表示為 0b10111(5位)。

2. 補 0 後變為 0b010111(6位)。

3. 進行奇偶位交換:0b010111 -> 0b101011。

4. 0b101011 轉為十進位即為 43。

解題思路

1. 將每兩個二進制位視為一個 4 進制位,簡化問題為 4 進制數的轉換。

2. 建立映射關係:00->00, 01->10, 10->01, 11->11,對應數組 [0, 2, 1, 3]。

3. 遍歷輸入的每個 4 進制位,使用映射數組進行轉換。

4. 將轉換後的 4 進制數重新組合為十進制結果。

實現

def swap_binary_bits_arithmetic(number):
    result = 0
    position = 0
    bit_swap_map = [0, 2, 1, 3]

    while number != 0:
        current_quad = number % 4
        swapped_quad = bit_swap_map[current_quad]
        result += swapped_quad * (4 ** position)
        number //= 4
        position += 1

    return result

def swap_binary_bits_bitwise(number):
    result = 0
    position = 0
    bit_swap_map = [0, 2, 1, 3]

    while number:
        current_quad = number & 3
        swapped_quad = bit_swap_map[current_quad]
        result |= swapped_quad << position
        number >>= 2
        position += 2

    return result