728x90
반응형
* 출처: 백준
1935번: 후위 표기식2
첫째 줄에 피연산자의 개수(1 ≤ N ≤ 26) 가 주어진다. 그리고 둘째 줄에는 후위 표기식이 주어진다. (여기서 피연산자는 A~Z의 영대문자이며, A부터 순서대로 N개의 영대문자만이 사용되며, 길이
www.acmicpc.net
내 풀이
calc()인자로 alpha 배열을 안넘겨주고 풀어서 틀렸었다.
public class Main {
static int N;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(in.readLine()); // 피연산자 개수
String s = in.readLine(); // 후위 연산식
int[] alpha = new int[N]; // 피연산자 대응값
for (int i = 0; i < N; i++) {
alpha[i] = Integer.parseInt(in.readLine());
}
// calc(s,alpha);
System.out.printf("%.2f", calc(s, alpha));
}
static double calc(String s, int[] alpha) {
int len = s.length();
double res = 0;
Stack<Double> stack = new Stack<>();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= 'A' && c <= 'Z') {
int cIdx = c - 'A';
double tmp = alpha[cIdx];
stack.push(tmp);
} else if (c == '+') {
double b = stack.pop();
double a = stack.pop();
res = a + b;
stack.push(res);
} else if (c == '-') {
double b = stack.pop();
double a = stack.pop();
res = a - b;
stack.push(res);
} else if (c == '*') {
double b = stack.pop();
double a = stack.pop();
res = a * b;
stack.push(res);
} else if (c == '/') {
double b = stack.pop();
double a = stack.pop();
res = a / b;
stack.push(res);
}
}
res = stack.pop();
return res;
}
}
728x90
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[문제] 백준 1018번 체스판 다시 칠하기 (0) | 2021.02.09 |
---|---|
[문제] 백준 2667번 단지번호 붙이기 (0) | 2021.02.08 |
[문제] 백준 1918번 후위표기식 (0) | 2021.02.07 |
[문제] 백준 10819번 차이를 최대로 (0) | 2021.02.05 |
[문제] 백준 2493번 탑 (0) | 2021.02.04 |