369 games (with.Java)
This article looks into the β369 Gameβ issue.
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
Iβm playing 369 games with my shy friends.
The 369 game is a game in which the numbers are numbered one by one starting from 1, and for numbers containing 3, 6, or 9, clapping as much as the number of 3, 6, or 9 is used instead of the number.
Complete the solution function so that when the number order that the mush must speak is given as a parameter, it returns the number of times the mush must clap.
Restrictions
- 1 β€ order β€ 1,000,000
Input/Output Example
order | result |
---|---|
3 | 1 |
29423 | 2 |
My solution to the problem
import java.util.*;
class Solution {
public int solution(int order) {
int answer = 0;
for(char str : Integer.toString(order).toCharArray()){
int temp = str - '0';
if(temp - 3 == 0 || temp - 6 == 0 || temp - 9 == 0){
answer++;
}
}
return answer;
}
}
Solution explanation
The reason for subtracting β0β from int temp = str - β0β; is to convert a character number to an integer type.
Character numbers are expressed as ASCII code values, and the ASCII code value of the number β0β is 48.
Therefore, you can convert a character number to an integer by subtracting β0β and the character number.
For example, if str is β3β, β3β - β0β evaluates to 51 - 48. This will have the same value as the integer number 3.
In other words, int temp = str - β0β; converts a character number to an integer.