stoi() 参考 http://t.csdn.cn/L8DMQ
原题逆波兰表达式求值_牛客题霸_牛客网 (nowcoder.com)
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(int i = 0; i < tokens.size(); i++){
string s = tokens[i];
if(s != "+" && s != "-" && s != "*" && s != "/")
st.push(stoi(s)); //遇到数字加入栈中
else{ //遇到符号,拿出栈中最近的两个元素计算
int num = st.top();
st.pop();
switch(s[0]){ //根据符号运算
case '+': st.top() += num; break; //结果存入前一个数
case '-': st.top() -= num; break;
case '*': st.top() *= num; break;
case '/': st.top() /= num; break;
}
}
}
return st.top(); //栈中最终留下的就是答案
}
};
[NOIP2013]表达式求值 (nowcoder.com)
如果是acm模式最好用这个方法
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,sum,ans;
char c;
scanf("%lld",&n);//先取出算式中的第一个数
while(scanf("%c%lld",&c,&m)!=EOF)
{
if(c=='+')
{
sum+=n;
n=m;
}
else if(c=='*')
{
n*=m;
}
sum%=10000;
n%=10000;
}
printf("%lld",(sum+n)%10000);
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/131421.html