蓝桥 表达式计算

    xiaoxiao2021-03-25  176

    问题描述   输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。 输入格式   输入一行,包含一个表达式。 输出格式   输出这个表达式的值。 样例输入 1-2+3*(4-5) 样例输出 -4 数据规模和约定   表达式长度不超过100,表达式运算合法且运算过程都在int内进行。

    #include <bits/stdc++.h> using namespace std; stack<int> s; stack<char> os; int solve(char a,char b) { if(b==')') return 0; if((a=='-'||a=='+')&&(b=='+'||b=='-')) return 0; if((a=='*'||a=='/')&&(b=='*'||b=='/')) return 0; if((a=='*'||a=='/')&&(b=='+'||b=='-')) return 0; return 1; } int main() { string ss; cin >> ss; os.push('#'); for(int i = 0; i < ss.length(); i++) { int sum=0; if(isdigit(ss[i])) { while(isdigit(ss[i])) { sum=sum*10+ss[i]-'0'; i++; } s.push(sum); i--; } else { if(solve(os.top(),ss[i])==1) os.push(ss[i]); else { while(solve(os.top(),ss[i])==0) { if(os.top()=='('&&ss[i]==')') { os.pop(); break; } int a = s.top(); s.pop(); int b = s.top(); s.pop(); char ch=os.top(); os.pop(); if(ch=='+') s.push(a+b); if(ch=='-') s.push(b-a); if(ch=='*') s.push(a*b); if(ch=='/') s.push(b/a); } if(ss[i]==')') continue; else { os.push(ss[i]); } } } } while(os.top()!='#') { char ch; ch = os.top(); os.pop(); int a = s.top(); s.pop(); int b = s.top(); s.pop(); if(ch=='+') s.push(a+b); if(ch=='-') s.push(b-a); if(ch=='*') s.push(a*b); if(ch=='/') s.push(b/a); } printf("%d\n",s.top() ); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1810.html

    最新回复(0)