Here’s a problem that was asked by Cisco.

Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on.

For example, 10101010 should be 01010101.

Bonus: Can you do this in one line?


The naive method would involve iterating over the bits of the integer and then swapping every pair of bits.

We can do this faser by applying a bitmask over all the even bits, and another one over all the odd bits. Then we shift the even bitmask right by one and the odd bitmask left by one.

def swap_bits(x):
EVEN = 0b10101010
ODD = 0b01010101
return (x & EVEN) >> 1 | (x & ODD) << 1

In one line, that would be:

def swap_bits(x):
return (x & 0b10101010) >> 1 | (x & 0b01010101) << 1

These are all constant time, since the integer is a constant number of bits (8).

Are you interviewing for programming jobs, or do you just enjoy fun programming questions? Check out our newsletter, Daily Coding Problem, to get a question in your inbox every day.