Given a non-negative integer, write a function that swaps its odd and even bits. That is, bit 0 should be swapped with bit 1, bit 2 with bit 3, and so on.
For example, if the input is 42
(which is 101010
in binary), the function should return 21
(which is 010101
in binary).
Note: On this day, April 27, as we celebrate innovations in technology, take a moment to appreciate how bit-level operations can lead to efficient algorithms!
function swapOddEvenBits(n: number): number
n
.n
.Input: 42
Output: 21