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 −
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