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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | #include<iostream> #include<vector> #include<stack> #include<string> int main() { std::string string; std::stack<char> _operator_stack; std::stack<int> num_stack; std::vector<char> sum; std::getline(std::cin, string); for (auto _ch : string) { if (0 <= _ch - '0' && _ch - '0' < 10) { sum.push_back(_ch); } else { if (_operator_stack.size() != 0) { while (_operator_stack.size() != 0 && (_operator_stack.top() == '*' || _operator_stack.top() == '/') && (_ch == '+' || _ch == '-')) { sum.push_back(_operator_stack.top()); _operator_stack.pop(); } if (_operator_stack.size()) { if (_operator_stack.top() == ')') { while (_operator_stack.top() != '(') { _operator_stack.pop(); if (!(_operator_stack.top() == ')' || _operator_stack.top() == '(')) { sum.push_back(_operator_stack.top()); } } _operator_stack.pop(); } } } _operator_stack.push(_ch); } } while (_operator_stack.size()) { sum.push_back(_operator_stack.top()); _operator_stack.pop(); } for (int i = 0; i < sum.size(); i++) { std::cout << sum[i] << ' '; } std::stack<int> numsum; for (auto i = 0; i < sum.size(); i++) { if (0 <= sum[i] - '0' && sum[i] - '0' < 10) { numsum.push(sum[i] - '0'); } else if (sum[i] == '+') { int temp1 = numsum.top(); numsum.pop(); int temp2 = numsum.top(); numsum.pop(); numsum.push(temp1 + temp2); } else if (sum[i] == '-') { int temp1 = numsum.top(); numsum.pop(); int temp2 = numsum.top(); numsum.pop(); numsum.push(temp2 - temp1); } else if (sum[i] == '*') { int temp1 = numsum.top(); numsum.pop(); int temp2 = numsum.top(); numsum.pop(); numsum.push(temp1 * temp2); } else if (sum[i] == '/') { int temp1 = numsum.top(); numsum.pop(); int temp2 = numsum.top(); numsum.pop(); numsum.push(temp1 / temp2); } } std::cout << std::endl<< numsum.top(); } | cs |
생각보다 간단히 구현이 끝나서 놀랐다.
어제는 하루종일 끙끙거려도 절대 답이 나오지 않는 문제였는데
오늘은 비교적 단숨에(2시간 정도)풀린 것 같다.
sollution
+ -를 하기 전에 항을 따로 연산해줘야 한다.
따라서 +나 -를 만날 때마다 스택에 있는 우선순위가 높은 연산자들을 모두 빼내며 숫자 뒤쪽에 출력한다.
그리고 +나 -는 맨 마지막에 출력한다.
이렇게 되면 항은 분리적으로 연산되며, +나 -를 만나기 전까지 항끼리는 연산되지 않는다.
스택을 이용한 사칙연산계산기는 재귀함수로도 풀 수 있을 것 같다.
이런 식으로도 생각할 수 있기 때문
하지만 재귀로는 풀지 않았다..
( ) 연산을 처리한 방법에 대해서 설명하겠다.
( )연산은 )을 만나면 (까지 스택에 있는 모든 연산자를 빼는 것으로 했다.
)을 만났을 때 직전 연산이 덧셈, 뺄셈 연산이라면 곱셈과 나눗셈 연산은 이미 다 출력되어있을 것이고.
아니라면 덧셈, 뺄셈 연산이 없기 때문에 연산자 우선순위에 문제가 발생하지 않는다.
'진행중인 프로젝트들' 카테고리의 다른 글
Simple Factory 예제 (0) | 2022.12.14 |
---|---|
데코레이터 패턴 c++로 짜봄 (0) | 2022.12.13 |
스택 사칙연산계산기에 대한 추가적인 설명 (0) | 2022.11.16 |
스택을 이용한 사칙연산계산기 구현 -1 중위표기법과 후위표기법 (0) | 2022.11.09 |
링크드 리스트 구현 (0) | 2022.11.07 |