Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Counting number of 9s encountered while counting up to n in JavaScript
We need to write a JavaScript function that counts how many times the digit "9" appears when counting from 0 to a given number n. For example, counting from 0 to 100 includes numbers like 9, 19, 29, 90, 91, 99, etc., where "9" appears multiple times.
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 the digit 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
How It Works
The solution uses a nested approach:
-
countChar function: Takes a string and a character, then counts occurrences of that character using
split()andreduce() - Main loop: Iterates from 0 to n, converting each number to string and counting "9"s
- Accumulation: Adds up all the "9"s found across all numbers
Alternative Approach
Here's a more concise version using regular expressions:
const countNineRegex = (num = 0) => {
let count = 0;
for(let i = 0; i <= num; i++){
const nineMatches = String(i).match(/9/g);
count += nineMatches ? nineMatches.length : 0;
}
return count;
};
console.log(countNineRegex(100)); // 20
console.log(countNineRegex(99)); // 20
console.log(countNineRegex(19)); // 2
20 20 2
Key Points
- Numbers can contain multiple "9"s (like 99 contains two "9"s)
- The function counts digit occurrences, not just numbers containing "9"
- Converting numbers to strings allows easy character manipulation
- Both approaches have O(n) time complexity
Conclusion
This solution effectively counts digit "9" occurrences by converting numbers to strings and using either array methods or regular expressions. The approach scales well for reasonable input sizes and handles multiple "9"s in single numbers correctly.
