Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 and swaps its adjacent binary bits to construct a new binary representation. The function should return the decimal equivalent of the modified binary.
How It Works
The algorithm converts the decimal number to binary, pairs adjacent bits, swaps each pair, and converts back to decimal. If the binary representation has an odd number of bits, we pad it with a leading zero to ensure complete pairs.
Example
Let's trace through number 13:
- 13 in binary:
1101 - Pair adjacent bits:
11and01 - Swap each pair:
11becomes11,01becomes10 - Result:
1110= 14 in decimal
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
Multiple Examples
Let's test with different numbers to understand the pattern:
const swapBits = (num) => {
let arr = num.toString(2).split('');
console.log(`${num} in binary: ${arr.join('')}`);
if(arr.length % 2){
arr.unshift('0');
console.log(`After padding: ${arr.join('')}`);
}
for(let i = 0; i < arr.length - 1; i = i + 2) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
}
const result = +('0b' + arr.join(''));
console.log(`After swapping: ${arr.join('')} = ${result}`);
console.log('---');
return result;
}
// Test cases
console.log('Result for 13:', swapBits(13));
console.log('Result for 10:', swapBits(10));
console.log('Result for 7:', swapBits(7));
Output
13 in binary: 1101 After swapping: 1110 = 14 --- Result for 13: 14 10 in binary: 1010 After swapping: 0101 = 5 --- Result for 10: 5 7 in binary: 111 After padding: 0111 After swapping: 0011 = 3 --- Result for 7: 3
Key Points
-
Binary Conversion:
toString(2)converts decimal to binary string - Padding: Add leading zero for odd-length binary to ensure complete pairs
- Swapping: Use array destructuring to swap adjacent elements efficiently
-
Binary to Decimal: The
0bprefix with unary+converts binary string to decimal
Conclusion
This algorithm efficiently swaps adjacent binary bits by converting to binary array, padding if necessary, swapping pairs, and converting back to decimal. The technique is useful for bit manipulation problems.
