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


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

Updated on: 19-Apr-2021

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements