Number of k (with.Java)
This is an article about the “Number of k (with.Java)” problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
In the numbers 1 to 13, 1 appears 6 times: 1, 10, 11, 12, and 13.
When integers i, j, and k are given as parameters, complete the solution function to return how many times k appears from i to j.
Restrictions
- 1 ≤ i < j ≤ 100,000
- 0 ≤ k ≤ 9
Input/Output Example
i | j | k | result |
---|---|---|---|
1 | 13 | 1 | 6 |
10 | 50 | 5 | 5 |
3 | 10 | 2 | 0 |
My solution to the problem
class Solution {
public int solution(int i, int j, int k) {
int answer = 0;
String str = "0";
char ch = '0';
for(int a = i; a <= j; a++){
str = Integer.toString(a);
for(int b = 0; b < str.length(); b++){
ch = str.charAt(b);
if(ch == Integer.toString(k).charAt(0)){
answer++;
}
}
}
return answer;
}
}
Solved review
Set the answer variable to its initial value of 0.
This variable represents the result.
Initialize the str variable to “0”. This variable is used to convert numbers into strings and store them.
Initialize the ch variable to ‘0’. This variable is used to check character by character in a string.
Execute the loop while increasing variable a from i to j.
Convert the value of a to a string and store it in the str variable.
Execute the loop while increasing the b variable from 0 to the length of str - 1.
Check the bth character (ch) of str.
If ch is equal to k, then increase the answer variable by 1.
When the loop ends, the answer variable is returned.
The code is implemented by converting each number within the input range into a string, checking each character of the string one by one, and comparing it with k.