2 条题解
-
0
Guest
-
1
思路
由于是后缀表达式,越靠前的数运算越靠后,符合先进后出的性质,故用栈。 每次读取字符,如果:
- 读取的是数,直接压栈。
- 读取的是符号,弹出栈的前两个,算完后压栈。
code
#include<bits/stdc++.h> using namespace std; string s; int ans,n=0; stack<int>st; int main(){ cin>>s; for(int i=0;i<s.size();i++){ if(s[i]=='@') break; if(isdigit(s[i])) n=n*10+s[i]-'0'; if(s[i]=='.') st.push(n),n=0; int num1,num2; if(s[i]=='+'){ num2=st.top(),st.pop(); num1=st.top(),st.pop(); st.push(num1+num2); } if(s[i]=='-'){ num2=st.top(),st.pop(); num1=st.top(),st.pop(); st.push(num1-num2); } if(s[i]=='*'){ num2=st.top(),st.pop(); num1=st.top(),st.pop(); st.push(num1*num2); } if(s[i]=='/'){ num2=st.top(),st.pop(); num1=st.top(),st.pop(); st.push(num1/num2); } } cout<<st.top(); }
-
0
#include<bits/stdc++.h> using namespace std; int main(){ stack<int> s; string a; cin>>a; int sum=0; for(int i=0;i<a.length();i++){ if(a[i]>='0'&&a[i]<='9'){ sum=sum*10+(a[i]-'0'); } else if(a[i]=='.'){ s.push(sum); sum=0; } else if(a[i]=='+'){ int a1=s.top(); s.pop(); int b1=s.top(); s.pop(); s.push(a1+b1); } else if(a[i]=='-'){ int a1=s.top(); s.pop(); int b1=s.top(); s.pop(); s.push(b1-a1); } else if(a[i]=='*'){ int a1=s.top(); s.pop(); int b1=s.top(); s.pop(); s.push(a1*b1); } else if(a[i]=='/'){ int a1=s.top(); s.pop(); int b1=s.top(); s.pop(); s.push(b1/a1); } if(a[i]=='@'){ break; } } cout<<s.top(); }
- 1
信息
- ID
- 273
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- 递交数
- 9
- 已通过
- 6
- 上传者