给一个表达式,从左到右计算(不考虑优先级), 再按优先级计算
总结
比后缀表达式简单,但还是回去看看怎么写后缀表达式比较好
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <stack> 6 using namespace std; 7 const int maxn = 20; 8 char str[maxn]; 9 int main() 10 { 11 //freopen("in.txt","r",stdin); 12 while(cin >> str){ 13 int t; 14 cin >> t; 15 int len = strlen(str); 16 stack<int>s; 17 s.push(str[0]-'0'); 18 for(int i = 1; i < len; i++){ 19 if(str[i] == '+') s.push(str[i+1]-'0'); 20 else if(str[i] == '*'){ 21 int k = s.top(); 22 s.pop(); 23 s.push(k * (str[i+1]-'0')); 24 } 25 } 26 int ans1 = 0, ans2 = 0; 27 while(!s.empty()){ 28 ans1 += s.top(); 29 s.pop(); 30 } 31 s.push(str[0]-'0'); 32 for(int i = 1; i < len; i++){ 33 if(str[i] == '+'){ 34 int k = s.top(); 35 s.pop(); 36 s.push(k+str[i+1]-'0'); 37 } 38 else if(str[i] == '*'){ 39 int k = s.top(); 40 s.pop(); 41 s.push(k*(str[i+1]-'0')); 42 } 43 } 44 ans2 = s.top(); 45 if(ans1 == t && ans2 != t) cout << "M" << endl; 46 else if(ans2 == t && ans1 != t) cout << "L" << endl; 47 else if( ans1 == ans2 && ans1 == t) cout << "U" << endl; 48 else cout << "I" << endl; 49 50 } 51 return 0; 52 }