OX Quiz (with.Java)
This is an article about the βOX Quiz (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
Quiz, a string array containing addition and subtraction formulas in the form of βX [operator] Y = Zβ, is given as a parameter.
Complete the solution function so that it returns an array containing βOβ in order if the formula is correct, and βXβ if it is incorrect.
Restrictions
- There is always a space between the operation symbol and the number. However, there is no space between the minus sign, which indicates a negative number, and the number.
- 1 β€ length of quiz β€ 10
- X, Y, and Z each represent an integer consisting of numbers from 0 to 9, and there can be a minus sign at the beginning of each number, which means a negative number.
- X, Y, Z do not start with 0 except 0.
- 10,000 β€ X, Y β€ 10,000
- 20,000 β€ Z β€ 20,000
- [Operator] is either + or -.
Input/Output Example
my_string | num1 |
---|---|
[β3 - 4 = -3β, β5 + 6 = 11β] | [βXβ, βOβ] |
[β19 - 6 = 13β, β5 + 66 = 71β, β5 - 15 = 63β, β3 - 1 = 2β] | [βOβ, βOβ, βXβ, βOβ] |
My solution to the problem
class Solution {
public String[] solution(String[] quiz) {
String[] answer = new String[quiz.length];
String[] temp = new String[quiz.length];
for(int i = 0; i < quiz.length; i++){
temp = quiz[i].split(" ");
if(temp[1].equals("+")){
if(Integer.valueOf(temp[0]) + Integer.valueOf(temp[2]) == Integer.valueOf(temp[4])){
answer[i] = "O";
}else{
answer[i] = "X";
}
}
if(temp[1].equals("-")){
if(Integer.valueOf(temp[0]) - Integer.valueOf(temp[2]) == Integer.valueOf(temp[4])){
answer[i] = "O";
}else{
answer[i] = "X";
}
}
}
return answer;
}
}
Solution explanation
The solution method analyzes each element of the given quiz array and initializes an answer array to store the results.
We also initialize a temp array for temporary use.
We then process each element of the quiz array through a for loop.
Each element is split based on whitespace and stored in the temp array.
If the second element of the temp array is β+β, convert the first and third elements to integers and check if their sum equals the fifth element.
If they are the same, βOβ is stored in the corresponding index of the answer array. If they are different, βXβ is stored.
If the second element of the temp array is β-β, we handle it the same way.
Finally, it returns an array of answers.