- μ€νμ μ΄μ©νμ¬ μ«μλ€μ μ μ₯νκ³ μ°μ°μκ° λμ¬ λ λ§λ€ μ€νμμ μ«μλ₯Ό 2κ° κΊΌλ΄μ νΉμ μ°μ°μλ₯Ό μ μ©νλ©΄ λλ€.
- μ€νμ κΈΈμ΄λ tokenμ μλ₯Ό λμ μ μμΌλ―λ‘ λμΌν κΈΈμ΄μ integer arrayλ‘ μ μΈνμ¬ stackμ λμ ν μ μλ€.
int[]
λ₯Ό μ¬μ©νλ©΄ Stack<Integer>
μΌλ‘ ꡬννμ λ λ³΄λ€ 1.5 ~ 2λ°° κ°λ λΉ λ₯΄λ€.
class Solution {
public int evalRPN(String[] tokens) {
int[] stack = new int[tokens.length];
int top = -1;
for (String token : tokens) {
char c = token.charAt(0);
int value = 0, lhs, rhs;
if (token.length() == 1 && (c < '0' || c > '9')) {
rhs = stack[top--];
lhs = stack[top--];
switch (c) {
case '+': value = lhs + rhs; break;
case '-': value = lhs - rhs; break;
case '*': value = lhs * rhs; break;
case '/': value = lhs / rhs; break;
}
stack[++top] = value;
} else if (c == '-') {
stack[++top] = -Integer.parseInt(token.substring(1));
} else {
stack[++top] = Integer.parseInt(token);
}
}
return stack[top];
}
}