4. 후위식 연산(postfix)
후위연산식이 주어지면 연산한 결과를 출력하는 프로그램
입력) 첫 줄에 후위연산식이 주어집니다.
출력) 연산한 결과를 출력합니다.
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static int solution(String str) {
int answer = 0;
Stack<Integer> stack = new Stack<>();
for (char x : str.toCharArray()) {
if (Character.isDigit(x)) {
stack.push(x-48);
} else {
int second = stack.pop();
int first = stack.pop();
if (x=='+') stack.push(first + second);
else if (x=='-') stack.push(first - second);
else if (x=='*') stack.push(first * second);
else stack.push(first / second);
}
}
answer = stack.get(0);
return answer;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
System.out.println(solution(str));
}
}
'0' 아스키코드 : 48
x-48 == Character.getNumericValue(x)
결과
입력
352+*9-
출력
12
'알고리즘(Java) > Stack & Queue' 카테고리의 다른 글
[알고리즘]Queue - 공주 구하기 (0) | 2021.08.07 |
---|---|
[알고리즘]Stack - 쇠막대기 (0) | 2021.08.05 |
[알고리즘]Stack - 크레인 인형뽑기(카카오) (0) | 2021.08.04 |
[알고리즘]Stack - 괄호문자 제거 (0) | 2021.08.04 |
[알고리즘]Stack - 올바른 괄호 (0) | 2021.08.04 |
댓글