thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

ByteByteGo: Swap Odd and Even Bits

β€’ 45 words β€’ 1 min β€’ updated

ByteByteGo: Swap Odd and Even Bits:

python
def swap_odd_and_even_bits(n: int) -> int:
    ans = 0
    shift = 0

    while n > 0:
        ans += ((n & 0b01) << 1) + ((n & 0b10) >> 1) << shift
        n >>= 2
        shift += 2

    return ans