Given a 64-bit integer, swap the bits at indices i and j.
- Let x = 1234 in decimal
- Let i = 3
- Let j = 7
MSB | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | LSB |
---|---|---|---|---|---|---|---|---|---|---|
1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 1 | 0 |
MSB | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | LSB |
---|---|---|---|---|---|---|---|---|---|---|
1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 0 |
The swapped number in decimal = 1114
def swap_bits(x, i, j):
bit_i = x >> i & 1
bit_j = x >> j & 1
if bit_i != bit_j:
x ^= 1 << i
x ^= 1 << j
return x
- Extract the i-th bit and j-th bit by shifting to the right
- If the swap is necessary, flip the bits to swap
- Extract the i-th bit
bit_i = x >> i & 1
- Extract the j-th bit
bit_j = x >> j & 1
- Check if the swap is necessary, which is if the bits are not equal to each other
if bit_i != bit_j:
- Flip the i-th bit
x ^= 1 << i
- Flip the j-th bit
x ^= 1 << j
- Return the decimal number with the swapped bits
return x