Replacing digits to form binary using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string of digits. Our function should replace any digit below 5 with '0' and any digit 5 and above with '1' and return the resulting string.

Example

Following is the code −

 Live Demo

const str = '262355677834342';
const convert = (str = '') => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = +str[i];
      if(el < 5){
         res += 0;
      }else{
         res += 1;
      };
   };
   return res;
};
console.log(convert(str));

Output

010011111100000
raja
Published on 17-Apr-2021 13:22:52
Advertisements