
https://school.programmers.co.kr/learn/courses/30/lessons/120902
구조는 맞췄으나 마지막에 temp의 남은 몫에 대한 계산이 없어서 틀린 문제다.
' '인 경우+, - 와 같은 연산자인 경우 +라면 더한다. -라면 뺀다. ' '일 때는 연산을 하고 StringBuilder()를 초기화해야 한다. int v = Integer.parseInt(temp.toString());
if (oper == ' ') {
total = v;
} else {
if(oper == '+') {
total += v;
} else { // '-'
total -= v;
}
}
class Solution {
public int solution(String my_string) {
char[] arr = my_string.toCharArray();
int total = 0;
StringBuilder temp = new StringBuilder();
char oper = ' ';
for(int i = 0; i < arr.length; i++) {
if(Character.isDigit(arr[i])) { // 숫자라면 그냥 더한다.
temp.append(arr[i]);
} else if (arr[i] == ' ') {
if(temp.length() == 0) continue;
int v = Integer.parseInt(temp.toString());
if (oper == ' ') {
total = v;
} else {
if(oper == '+') {
total += v;
} else { // '-'라는 뜻이다.
total -= v;
}
}
temp = new StringBuilder();
} else {
oper = arr[i]; // 연산자를 저장한다.
}
}
System.out.println(temp);
if(temp.length() > 0) {
int v = Integer.parseInt(temp.toString());
if(oper == ' ') total = v;
else if (oper == '+') total += v;
else total -= v;
}
return total;
}
}