Counting number of 9s encountered while counting up to n in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number n. Our function should count and return the number of times we will have to use 9 while counting from 0 to n.

Example

Following is the code −

 Live Demo

const num = 100;
const countNine = (num = 0) => {
   const countChar = (str = '', char = '') => {
      return str
      .split('')
      .reduce((acc, val) => {
         if(val === char){
            acc++;
         };
         return acc;
      }, 0);
   };
   let count = 0;
   for(let i = 0; i <= num; i++){
      count += countChar(String(i), '9');
   };
   return count;
};
console.log(countNine(num));

Output

Following is the console output −

20
raja
Published on 19-Apr-2021 08:24:52
Advertisements