Replacing digits to form binary using JavaScript


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

Updated on: 17-Apr-2021

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements