Advertisement
hieudoan

Reverse Polish Notation

Jul 2nd, 2019
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. /*
  2.  *hieudoan7 18:19 02/07/2019
  3.  */
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. int getPriority(char c){
  8.     if(c == '*' || c=='/') return 2;
  9.     else if (c=='+' || c=='-') return 1;
  10.     else if (c=='(' || c==')') return 0;
  11.     else return -1; //number
  12. }
  13.  
  14. string toRPN(string s){
  15.     stack<char> st;
  16.     string ans = "";
  17.     for(int i=0; i<s.length(); i++){
  18.         int prior = getPriority(s[i]);
  19.         if(prior == -1) ans += s[i];
  20.         else { //operator
  21.             if(s[i]=='(') st.push(s[i]);
  22.             else {
  23.                 if(s[i]==')') {
  24.                     while(st.top()!='(') {
  25.                         ans+=st.top();
  26.                         st.pop();
  27.                     }
  28.                     st.pop(); //pop (
  29.                 }
  30.                 else {
  31.                     while(!st.empty() && prior <= getPriority(st.top())){
  32.                         ans += st.top();
  33.                         st.pop();
  34.                     }
  35.                     st.push(s[i]);
  36.                 }
  37.             }
  38.         }
  39.     }
  40.     while(!st.empty()) {
  41.         ans += st.top();
  42.         st.pop();
  43.     }
  44.     return ans;
  45. }
  46.  
  47. int aOpeb(int a, int b, char ope){
  48.     if(ope == '*') return a*b;
  49.     if(ope == '/') return a/b;
  50.     if(ope == '+') return a+b;
  51.     if(ope == '-') return a-b;
  52.  }
  53.  
  54. int calculate (string RPN){
  55.     int ans = 0;
  56.     stack<int> st;
  57.     for(int i=0; i<RPN.length(); i++){
  58.         int prior = getPriority(RPN[i]);
  59.         if(prior == -1) st.push(RPN[i]-'0'); //mọi toán hạng đều có 1 chữ số ;v
  60.         else {
  61.             int b = st.top(); st.pop();
  62.             int a = st.top(); st.pop();
  63.             st.push(aOpeb(a,b,RPN[i]));
  64.         }
  65.     }
  66.     return st.top();
  67. }
  68.  
  69. int main()
  70. {
  71.     string S = "3+5*(6-3)+1";
  72.     string RPN = toRPN(S);
  73.     cout << RPN <<endl;
  74.     cout << S << " = " << calculate(RPN) <<endl;
  75.  
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement