Swap Odd Even Bits

Bit Manipulation Swapping Algorithm Easy Coding Problem

Problem: Swap Odd and Even Bits

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).

Requirements:

  • Use bit manipulation techniques to solve the problem efficiently.
  • Aim for a solution that runs in constant time.

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 Signature:

function swapOddEvenBits(n: number): number

Input:

  • A non-negative integer n.

Output:

  • An integer obtained after swapping the odd and even bits of n.

Example:

Input: 42
Output: 21