Simple Counting [Edabit]

Edabit

Mubashir needs your help to count a specific digit in an array.

You have to create a function that takes two integers n and d and makes an array of squares of all numbers from 0…<= n and returns the count of the digits d in the array.

Examples

countDigits(10, 1) ➞ 4
// Squared array from 0 to 10 = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
// Digit 1 appeared 4 times in the array

countDigits(25, 2) ➞ 9

countDigits(10, 1) ➞ 4

Notes

d will always be 0<=d<10.

Solution:

function countDigits(n, d) {
  let sol = 0;
  for (let i = 0; i <= n; i++) {
    let temp = i * i;
    if (temp == 0 && d == 0) {
      sol++;
    }
    while (temp) {
      if (d == temp % 10) {
        sol++;
      }
      temp = Math.floor(temp / 10);
    }
  }
  return sol;
}

Leave a comment