Contents

OX Quiz (with.Java)

   Apr 18, 2024     3 min read

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_stringnum1
[β€œ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.