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
Replacing digits to form binary using JavaScript
We need to write a JavaScript function that converts a string of digits into a binary-like representation by replacing digits below 5 with '0' and digits 5 and above with '1'.
Problem Statement
Given a string containing digits, transform it using these rules:
- Digits 0, 1, 2, 3, 4 ? '0'
- Digits 5, 6, 7, 8, 9 ? '1'
Using For Loop
const str = '262355677834342';
const convert = (str = '') => {
let res = '';
for(let i = 0; i < str.length; i++){
const el = +str[i];
if(el < 5){
res += 0;
} else {
res += 1;
}
}
return res;
};
console.log(convert(str));
010011111100000
Using Array Methods
const str = '262355677834342';
const convertWithMap = (str = '') => {
return str.split('').map(digit => +digit < 5 ? '0' : '1').join('');
};
console.log(convertWithMap(str));
010011111100000
Using Regular Expression
const str = '262355677834342';
const convertWithRegex = (str = '') => {
return str.replace(/[0-4]/g, '0').replace(/[5-9]/g, '1');
};
console.log(convertWithRegex(str));
010011111100000
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| For Loop | Good | Fastest | Medium |
| Array Methods | Excellent | Good | Short |
| Regular Expression | Good | Good | Shortest |
Conclusion
All three methods effectively convert digits to binary representation. The array method offers the best balance of readability and conciseness, while the for loop provides optimal performance for large strings.
Advertisements
