字符串表达式运算(西安交通大学机试题)
字符串表达式运算
查看题解 查看答案
题目描述
Time Limit: 1000 ms
Memory Limit: 256 mb
给一个字符串,例-6+11+23-6,输出结果。这个很简单,只有加减运算,没有乘除
输入输出格式
输入描述:
输出描述:
输入输出样例
输入样例#:
-6+11+23-6
输出样例#:
22
题目来源
西安交通大学机试题
#include<bits/stdc++.h> using namespace std; int main(){ int n; string str; while(cin>>str){ stack<int>s; n = str.size(); int temp = 0; char pre = '+'; for(int i = 0; i < n; i ++){ if(str[i] >= '0' && str[i] <= '9'){//是数字就一直加 temp = temp * 10 + (str[i] - '0'); continue; } if(pre == '+'){ s.push(temp); // cout<<temp<<endl; pre = str[i]; temp = 0; } else{ s.push(-temp); // cout<<temp<<endl; pre = str[i]; temp = 0; } } if(pre == '+'){ s.push(temp); // cout<<temp<<endl; } else{ s.push(-temp); // cout<<temp<<endl; } int count = 0; while(!s.empty()){ count += s.top(); s.pop(); } cout<<count<<endl; } }