Control 'Z' (with. Java)
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
s | result |
---|---|
β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.