Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements