Home  >  Article  >  Web Front-end  >  Encoding a numeric string into a string of 0s and 1s in JavaScript

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

PHPz
PHPzforward
2023-08-24 08:13:08651browse

在 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));

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete