# Depend the Digit in Java

## The problem#

Take an integer `n (n >= 0)` and a digit `d (0 <= d <= 9)` as an integer. Sq. all numbers `okay (0 <= okay <= n)` between 0 and n. Depend the numbers of digits `d` used within the writing of all of the `okay**2`. Name `nb_dig` (or nbDig or …) the perform taking `n` and `d` as parameters and returning this rely.

#### Examples:#

``````n = 10, d = 1, the okay*okay are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We're utilizing the digit 1 in 1, 16, 81, 100. The overall rely is then 4.

nb_dig(25, 1):
the numbers of curiosity are
1, 4, 9, 10, 11, 12, 13, 14, 19, 21 which squared are 1, 16, 81, 100, 121, 144, 169, 196, 361, 441
so there are 11 digits `1` for the squares of numbers between 0 and 25.
``````

Notice that `121` has twice the digit `1`.

## The answer in Java code#

Possibility 1:

``````public class CountDig {

public static int nbDig(int n, int d) {
int sum = 0;
for (int i = 0; i <= n; i++) {
sum += countOfDigit((int) Math.pow(i, 2), d);
}
return sum;
}

public static int countOfDigit(int n, int d) {
int rely = 0;
do {
if (n % 10 == d)
rely ++;
n /= 10;
} whereas (n > 0);
return rely;
}
}
``````

Possibility 2:

``````import java.util.stream.IntStream;

public class CountDig {

public static int nbDig(int n, int d) {

return (int) IntStream
.rangeClosed(0, n)
.map(i -> i * i)
.flatMap(i -> String.valueOf(i).chars())
.mapToObj(i -> (char)i)
.mapToInt(Character::getNumericValue)
.filter(i -> i == d)
.rely();
}
}
``````

Possibility 3:

``````public class CountDig {

public static int nbDig(int n, int d) {
int needle = String.valueOf(d).charAt(0);
int rely = 0;
for (int i = 0; i <= n; i++) {
String haystack = String.valueOf(i * i);
rely += (int) haystack.chars().filter(ch -> ch == needle).rely();
}
return rely;
}
}
``````

## Take a look at circumstances to validate our answer#

``````import static org.junit.Assert.*;

import org.junit.Take a look at;

public class CountDigTest {
non-public static void testing(int precise, int anticipated) {
assertEquals(anticipated, precise);
}
@Take a look at
public void take a look at() {
System.out.println("Fastened Checks nbDig");
testing(CountDig.nbDig(5750, 0), 4700);
testing(CountDig.nbDig(11011, 2), 9481);
testing(CountDig.nbDig(12224, 8), 7733);
testing(CountDig.nbDig(11549, 1), 11905);
}
}
``````