
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Specific Digits in Squares of Numbers using JavaScript
Problem
We are required to write a JavaScript function that takes in an integer n (n >= 0) and a digit d (0 <= d <= 9)
Our function should square all numbers k (0 <= k <= n) between 0 and n and count the numbers of digits d used in the writing of all the k**2.
Example
Following is the code −
const n = 25; const d = 1; const countDigits = (n, d) => { let k = 0, count = 0; d = d.toString(); while (k <= n) { let a = 0; let s = (k*k).toString(); for(let i = 0; i < s.length; i++) if(s[i] == d) a++; if (a > 0) { count += a; }; k++; }; return count; }; console.log(countDigits(n, d));
Output
11
Advertisements