UVALive6833 - Miscalculation

 给一个表达式,从左到右计算(不考虑优先级), 再按优先级计算

总结

比后缀表达式简单,但还是回去看看怎么写后缀表达式比较好

 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 }

 

转载于:https://www.cnblogs.com/kikii233/p/5970641.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值