- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Constructing a string of alternating 1s and 0s of desired length using JavaScript
- Check if a string has m consecutive 1s or 0s in Python
- Query-string encoding of a Javascript Object
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Largest subarray with equal number of 0s and 1s in C++
- Count Substrings with equal number of 0s, 1s and 2s in C++
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Segregate all 0s on right and 1s on left in JavaScript
- Encoding string to reduce its size in JavaScript
- Encoding string based on character frequency in JavaScript
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Splitting a string into parts in JavaScript
- Segregating a string into substrings - JavaScript
- MySQL query to count the number of 0s and 1s from a table column and display them in two columns?
- XOR counts of 0s and 1s in binary representation in C++

Advertisements