Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- *hieudoan7 18:19 02/07/2019
- */
- #include <bits/stdc++.h>
- using namespace std;
- int getPriority(char c){
- if(c == '*' || c=='/') return 2;
- else if (c=='+' || c=='-') return 1;
- else if (c=='(' || c==')') return 0;
- else return -1; //number
- }
- string toRPN(string s){
- stack<char> st;
- string ans = "";
- for(int i=0; i<s.length(); i++){
- int prior = getPriority(s[i]);
- if(prior == -1) ans += s[i];
- else { //operator
- if(s[i]=='(') st.push(s[i]);
- else {
- if(s[i]==')') {
- while(st.top()!='(') {
- ans+=st.top();
- st.pop();
- }
- st.pop(); //pop (
- }
- else {
- while(!st.empty() && prior <= getPriority(st.top())){
- ans += st.top();
- st.pop();
- }
- st.push(s[i]);
- }
- }
- }
- }
- while(!st.empty()) {
- ans += st.top();
- st.pop();
- }
- return ans;
- }
- int aOpeb(int a, int b, char ope){
- if(ope == '*') return a*b;
- if(ope == '/') return a/b;
- if(ope == '+') return a+b;
- if(ope == '-') return a-b;
- }
- int calculate (string RPN){
- int ans = 0;
- stack<int> st;
- for(int i=0; i<RPN.length(); i++){
- int prior = getPriority(RPN[i]);
- if(prior == -1) st.push(RPN[i]-'0'); //mọi toán hạng đều có 1 chữ số ;v
- else {
- int b = st.top(); st.pop();
- int a = st.top(); st.pop();
- st.push(aOpeb(a,b,RPN[i]));
- }
- }
- return st.top();
- }
- int main()
- {
- string S = "3+5*(6-3)+1";
- string RPN = toRPN(S);
- cout << RPN <<endl;
- cout << S << " = " << calculate(RPN) <<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement