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


Problem

We are required to write a JavaScript function that takes in a string that represents a decimal number.

Our function should convert/encode this decimal into binary based on the following rules.

For each digit d of n

  • Let k be the number of bits of d
  • We write k-1 times the digit 0 followed by the digit 1
  • We write digit d as a binary string, with the rightmost bit being the least significant
  • Lastly, we concatenate the result of b) and c) to get the coding of d

At last, we concatenate all the results got for the digits of n.

Thus, code 2 as 0110 and 3 as 0111

Example

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

Following is the console output −

001111001111011101110001100000011000001101001101

Updated on: 19-Apr-2021

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements