Contents

Control 'Z' (with. Java)

   Feb 19, 2024     2 min read

This article looks into the β€œControl β€˜Z’” 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

You are given a string containing numbers and β€œZ” separated by spaces.

I’m trying to add numbers in a string one after another.

At this time, if β€œZ” appears, it means subtracting the number that was added just before.

Given a string s consisting of a number and β€œZ”, complete the solution function so that it returns the value the wizard found.

Restrictions

  • Length of 1 ≀ s ≀ 200
  • -1,000 < number of elements in s < 1,000
  • s consists of a number, β€œZ”, and a space.
  • The numbers in s and β€œZ” are separated from each other by a space.
  • Consecutive spaces are not allowed.
  • There are no numbers starting with 0 except 0. -s does not start with β€œZ”.
  • There are no spaces at the beginning or end of s.
  • β€œZ” never appears consecutively.

Input/Output Example

sresult
β€œ1 2 Z 3”4
β€œ10 20 30 40”100

My solution to the problem

class Solution {
     public int solution(String s) {
         int answer = 0;
         String[] temp = s.split(" ");
         int tempInt = 0;
         for(String a : temp){
             if(a.equals("Z")){
                 answer -= tempInt;
             } else{
                 answer += Integer.parseInt(a);
                 tempInt = Integer.parseInt(a);
             }
         }
         return answer;
     }
}

Solution explanation

  • String separation: Split the given string s based on spaces through s.split(β€œ β€œ) and store it in the string array temp.
  • Number and β€˜Z’ processing: While traversing the array temp through a for statement, if each element is β€˜Z’, the previously stored value tempInt is subtracted from the sum answer to date, and if it is a number, converted to an integer and the current value is calculated. Add to the sum.
  • Remember previous value: Every time β€˜Z’ appears, subtraction is performed from the current sum, so the previously stored integer value is remembered in tempInt and used.

Code Advantages

  • Simple logic: The logic for processing strings and calculating sums using simple patterns is intuitive.
  • Array utilization: By separating the string and storing it in an array, each element can be processed sequentially.

Code Disadvantages

  • Insufficient error handling: Only cases where β€˜Z’ and numbers appear are considered, and error handling for input values is insufficient. It would be a good idea to add validation, etc.
  • Fixed separation criteria: In the current code, strings are separated based on spaces, but various other cases are not considered. It is necessary to add logic to handle various cases depending on the format of the input data.