-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountDig.java
34 lines (29 loc) · 1.14 KB
/
CountDig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer. Square all numbers k (0 <= k <= n) between 0 and n. Count the numbers of digits d used in the writing of all the k**2. Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.
#Examples:
n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in 1, 16, 81, 100. The total count is then 4.
nb_dig(25, 1):
the numbers of interest 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.
Note that 121 has twice the digit 1.
*/
public class CountDig {
public static int nbDig(int n, int d) {
// your code
int count=0;
for(int i=0;i<=n;i++){
int a=i*i;
String dummy = ""+a;
for(int j=0;j<dummy.length();j++){
a = Integer.parseInt(""+dummy.charAt(j));
if(a == d) count++;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(nbDig(25, 1));
}
}