이 전에 포스팅했던 계산기 문제에서 너무 야매로 연산식을 변환했던 거 같애서 다시 코딩해봤습니다.
+ 또는 - 일 때, 이전 연산자가 괄호가 아니면 이전 연산자를 후위식에 추가하고 현제 연산자는 스택에 들어갑니다.
괄호면 현제 연산자가 스택에 들어가기만 합니다.
* 또는 / 일 때, 이전 연산자가 * 또는 /이면 이전 연산자를 후위식에 추가하고 현제 연산자는 스택에 들어갑니다.
아니면 현제 연산자가 스택에 들어가기만 합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
char operation[1000];
int top = 0;
int main() {
string s;
string postfix;
cin >> s;
int size = s.size();
for (int i = 0; i < size; i++) {
char c = s[i];
if (c <= '9' && c >= '0')
postfix += c;
else if (c == '+' || c == '-') {
if (top > 0) {
char p_operation = operation[--top];
if(p_operation == '(') {
operation[top++] = p_operation;
operation[top++] = c;
}
else {
postfix += p_operation;
operation[top++] = c;
}
}
else {
operation[top++] = c;
}
}
else if (c == '*' || c == '/') {
if (top > 0) {
char p_operation = operation[--top];
if (p_operation == '*' || p_operation == '/') {
postfix += p_operation;
operation[top++] = c;
}
else{
operation[top++] = p_operation;
operation[top++] = c;
}
}
else {
operation[top++] = c;
}
}
else if (c == '(') {
operation[top++] = c;
}
else if (c == ')') {
while (1) {
char p = operation[--top];
if (p == '(')
break;
else
postfix += p;
}
}
}
while (--top >= 0) { // 마지막에 남은 연산자들 넣기
postfix += operation[top];
}
cout << postfix << endl;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
h |
의견이 있으시거나 수정해야할 부분이 있으면 편하게 공유 부탁드립니다!
'전체 > 알고리즘 문제풀이' 카테고리의 다른 글
백준 15684. 사다리 조작 (0) | 2019.04.11 |
---|---|
SW Expert 1232. [S/W 문제해결 기본] 9일차 - 사칙연산(D4) (0) | 2019.04.04 |
SW Expert 1227. [S/W 문제해결 기본] 7일차 - 미로2 (D4) (0) | 2019.04.04 |
SW Expert 1224. [S/W 문제해결 기본] 6일차 - 계산기3(D4) (0) | 2019.04.02 |
SW Expert 1223. [S/W 문제해결 기본] 6일차 - 계산기2(D4) (0) | 2019.04.02 |