后缀表达式求值
GuanYiQiao原题链接:跳转点此
我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| #include <bits/stdc++.h> using namespace std;
int getNum(string s) { stack<int> exp; int len=s.length(); int i=0;
while(i<len) { if(s[i]=='.') { i++; continue; } else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){ if(s[i]=='+'&&!exp.empty()) { int num1=exp.top(); exp.pop(); int num2=exp.top(); exp.pop(); int sum=num1+num2; exp.push(sum); i++; continue; } else if(s[i]=='-'&&!exp.empty()) { int num1=exp.top(); exp.pop(); int num2=exp.top(); exp.pop(); int dif=num2-num1; exp.push(dif); i++; continue; } else if(s[i]=='*'&&!exp.empty()) { int num1=exp.top(); exp.pop(); int num2=exp.top(); exp.pop(); int pro=num1*num2; exp.push(pro); i++; continue; } else if(s[i]=='/'&&!exp.empty()) { int num1=exp.top(); exp.pop(); int num2=exp.top(); exp.pop(); int com=num2/num1; exp.push(com); i++; continue; } } else{ string num=""; while(i<len&&s[i]>='0'&&s[i]<='9') { num.push_back(s[i]); i++; } if(!num.empty()) { int number=stoi(num); exp.push(number); } } } int ans=exp.top(); exp.pop(); return ans; }
int main() { string s; cin>>s; string str=""; for(int i=0;i<s.length();i++) { if(s[i]!='@') { str+=s[i]; } else if(s[i]=='@') { int ans=getNum(str); cout<<ans<<"\n"; str=""; continue; } } return 0; }
|
本题主要考察栈的应用 我这个是第一遍写的直接ac没再管 所以就代码比较复杂 其实优化一下不需要这么多行
[视频内嵌代码]