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 −
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