A Neat Bitwise Trick For Swapping Even and Odd Bits
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.
10101010 should be
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.
In one line, that would be:
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.
Ace your programming interview
Get a coding problem every day in your inbox!