题目:从键盘读入一个后缀表达式(字符串),只含有0-9组成的运算数及加(+)、减(—)、乘(*)、除(/)四种运算符。每个运算数之间用一个空格隔开,不需要判断给你的表达式是否合法。以@作为结束标志。
提示:输入字符串长度小于250,参与运算的整数及结果之绝对值均在264 范围内,如有除法保证能整除。
#include<bits/stdc++.h>
using namespace std;
stack<long long>s;
string str;
int len;
long long x,a,b;
int main(){
getline(cin,str);
int len=str.size();
for(int i=1;i<=len;i++){
x=0;
if(str[i]=='+'){
a=s.top();
s.pop();
b=s.top();
s.pop();
s.push(a+b);
}
else if(str[i]=='-'){
a=s.top();
s.pop();
b=s.top();
s.pop();
s.push(b-a);
}
else if(str[i]=='*'){
a=s.top();
s.pop();
b=s.top();
s.pop();
s.push(a*b);
}
if(str[i]=='/'){
a=s.top();
s.pop();
b=s.top();
s.pop();
s.push(b/a);
}
while(str[i]>='0'&&str[i]<='9'){
x=x*10+str[i]-48;
if(str[i+1]==' '){
s.push(x);
x=0;
}
i++;
}
}
cout<<s.top();
return 0;
}