Swapping adjacent binary bits of a decimal to yield another decimal using JavaScript


Problem

We are required to write a JavaScript function that takes in a number.

Our function should iterate through the binary equivalent of the number and swap its adjacent bits to construct a new binary. And then finally our function should return the decimal equivalent of the new binary.

Example

Following is the code −

 Live Demo

const num = 13;
const swapBits = (num) => {
   let arr = num.toString(2).split('');
   if(arr.length % 2){
      arr.unshift(0);
   }
   for(let i = 0; i < arr.length - 1; i = i + 2) {
      [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
   }
   return +('0b' + arr.join(''));
}
console.log(swapBits(num));

Output

14

Updated on: 20-Apr-2021

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements