Home > Article > Web Front-end > Encoding a numeric string into a string of 0s and 1s in JavaScript
We need to write a JavaScript function that accepts a string representing a decimal number.
Our function should convert/encode this decimal number to binary based on the following rules.
For each digit d in n
Finally, we concatenate all the resulting numbers of n.
So encoding 2 is 0110 and 3 is 0111
The following is the code -
const str = '77338855'; const encodeNumString = (str = '') => { const buildarray = (string = '') => { let n = string.split(''), res = ''; n.forEach(x => { let num = Number(x).toString(2); num = '0'.repeat(num.length -1) + '1' + num; res += num; }); return res; } const arr = []; let res = ""; for (let i = 0; i < 10; i++){ arr.push(buildarray(String(i))); }; while (str.length){ for (let i = 0; i < 10; i++) { if (str.startsWith(arr[i])) { res += String(i); str = str.slice(arr[i].length); break; } } } return res; }; console.log(encodeNumString(str));
The following is the control Station output-
001111001111011101110001100000011000001101001101
The above is the detailed content of Encoding a numeric string into a string of 0s and 1s in JavaScript. For more information, please follow other related articles on the PHP Chinese website!