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
Inverse operation in JavaScript
The inverse operation on a binary string involves flipping each bit: converting all 0s to 1s and all 1s to 0s. This is a common operation in computer science and digital logic.
Understanding Binary Inverse
Binary inverse (also called bitwise NOT or complement) transforms each digit in a binary string to its opposite value. For example, '1101' becomes '0010'.
Method 1: Using Array Methods
We can split the string into individual characters, transform each one, and join them back:
const num = '1101';
const n = '11010111';
const inverseBinary = (binary) => {
return binary.split("").map(el => {
return `${1 - parseInt(el, 10)}`;
}).join("");
};
console.log(inverseBinary(num));
console.log(inverseBinary(n));
0010 00101000
Method 2: Using String Replace
A simpler approach uses regular expressions to replace all occurrences:
const inverseBinaryReplace = (binary) => {
return binary.replace(/0/g, 'X').replace(/1/g, '0').replace(/X/g, '1');
};
console.log(inverseBinaryReplace('1101'));
console.log(inverseBinaryReplace('11010111'));
0010 00101000
Method 3: Using Ternary Operator
For better readability, we can use a ternary operator:
const inverseBinaryTernary = (binary) => {
return binary.split("").map(bit => bit === '0' ? '1' : '0').join("");
};
console.log(inverseBinaryTernary('1101'));
console.log(inverseBinaryTernary('11010111'));
0010 00101000
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| Array Methods | Moderate | Good | Medium |
| String Replace | Good | Fair | Short |
| Ternary Operator | Excellent | Good | Short |
Conclusion
Binary inverse operations are straightforward in JavaScript. The ternary operator approach offers the best balance of readability and performance for most use cases.
