Swap bits - Coding interview question
A few days ago, I came across the following coding interview question (using Python).
Problem:
Given a 32-bit integer, swap the 1st and 2nd bit, 3rd and 4th bit, up til the 31st and 32nd bit.
Here's some starting code and an example:
def swap_bits(num):
# Fill this in.
print(f"0b{swap_bits(0b10101010101010101010101010101010):032b}")
# 0b01010101010101010101010101010101
My Solution:
def swap_bits(num):
num_out = 0
for ii in range(16):
num_out += (num & (2**(2*ii))) << 1
num_out += (num & (2**(2*ii+1))) >> 1
return num_out
print(f"0b{swap_bits(0b10101010101010101010101010101010):032b}")
# Output:
# 0b01010101010101010101010101010101
My Question to You:
Do you have any suggestions for improvement, in terms of efficiency, length of code, readability, or whatever. I will highly appreciate your feedback. Thanks!