Home > Web Front-end > JS Tutorial > body text

Encoding a numeric string into a string of 0s and 1s in JavaScript

PHPz
Release: 2023-08-24 08:13:08
forward
621 people have browsed it

在 JavaScript 中将数字字符串编码为 0 和 1 的字符串

Question

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

  • Let k be the number of digits in d
  • We multiply k-1 by the number 0 followed by the number 1
  • We write the number d as a binary string, the rightmost bit is the least significant bit
  • Finally, we concatenate the results of b) and c) to get the encoding of d

Finally, we concatenate all the resulting numbers of n.

So encoding 2 is 0110 and 3 is 0111

Example

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));
Copy after login

Output

The following is the control Station output-

001111001111011101110001100000011000001101001101
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!