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

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 20-Apr-2021 09:21:35
Advertisements