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
Selected Reading
JavaScript Reverse the order of the bits in a given integer
We are required to write a JavaScript program that reverses the order of the bits in a given integer.
For example ?
56 -> 111000 after reverse 7 -> 111
Another example,
234 -> 11101010 after reverse 87 -> 1010111
How It Works
The algorithm converts the number to binary, reverses the binary string, and converts back to decimal:
- Convert number to binary string using
toString(2) - Split into array, reverse, and join back
- Parse reversed binary string to decimal using
parseInt(reversedBinary, 2)
Example
const num1 = 789;
const num = 43;
const reverseBits = (num = 1) => {
const str = num.toString(2);
const arr = str.split('').reverse();
const arrStr = arr.join('');
const reversedNum = parseInt(arrStr, 2);
return reversedNum;
}
console.log("Original:", num, "-> Binary:", num.toString(2));
console.log("Reversed bits result:", reverseBits(num));
console.log();
console.log("Original:", num1, "-> Binary:", num1.toString(2));
console.log("Reversed bits result:", reverseBits(num1));
Original: 43 -> Binary: 101011 Reversed bits result: 53 Original: 789 -> Binary: 1100010101 Reversed bits result: 675
Step-by-Step Breakdown
const reverseBitsDetailed = (num) => {
console.log("Input number:", num);
const binary = num.toString(2);
console.log("Binary representation:", binary);
const reversed = binary.split('').reverse().join('');
console.log("Reversed binary:", reversed);
const result = parseInt(reversed, 2);
console.log("Result as decimal:", result);
return result;
}
reverseBitsDetailed(56);
Input number: 56 Binary representation: 111000 Reversed binary: 000111 Result as decimal: 7
Optimized Version
const reverseBitsOptimized = (num) => {
return parseInt(num.toString(2).split('').reverse().join(''), 2);
}
// Test with multiple numbers
const testNumbers = [56, 234, 43, 789];
testNumbers.forEach(num => {
console.log(`${num} -> ${reverseBitsOptimized(num)}`);
});
56 -> 7 234 -> 87 43 -> 53 789 -> 675
Conclusion
Reversing bits involves converting to binary, reversing the string, and parsing back to decimal. This technique is useful in algorithms requiring bit manipulation and cryptographic operations.
Advertisements
