- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements