整数算术表达式求值
描述:
求由+-*/()组成的整数算术表达式的值。如1+2*3=7,(1+2)*3=9。除法运算,除不尽时向下取整,如(1+2)/2+1=2。不考虑数值溢出。不考虑除数为0。不考虑括号嵌套。
运行时间限制: 10 Sec
内存限制: 128 MByte
输入:
一行字符串,长度小于128个字节
输出:
计算结果,整数
样例输入:
1+3+4+5
样例输出:
描述:
求由+-*/()组成的整数算术表达式的值。如1+2*3=7,(1+2)*3=9。除法运算,除不尽时向下取整,如(1+2)/2+1=2。不考虑数值溢出。不考虑除数为0。不考虑括号嵌套。
运行时间限制: 10 Sec
内存限制: 128 MByte
输入:
一行字符串,长度小于128个字节
输出:
计算结果,整数
样例输入:
1+3+4+5
样例输出:
13
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
bool compare(char a,char b)//a>=b,return 1;
{
if(a=='*'||a=='/')
return true;
else
{
if(b=='+'||b=='-')
return true;
else
return false;
}
}
int main()
{
char opera;
int num;
vector<int> input;
stack<char> s;
while((opera=cin.get())!='\n')
{
if(opera=='+'||opera=='-'||opera=='*'||opera=='/')
{
while(!s.empty()&&s.top()!='('&&compare(s.top(),opera))
{
input.push_back(s.top()-'0');
s.pop();
}
s.push(opera);
}
else if(opera=='('||opera==')')
{
if(opera=='(')
s.push(opera);
else
{
while(s.top()!='(')
{
input.push_back(s.top()-'0');
s.pop();
}
s.pop();
}
}
else
{
cin.unget();
cin>>num;
input.push_back(num);
}
}
while(!s.empty())
{
input.push_back(s.top()-'0');
s.pop();
}
stack<int> out;
for(int i=0;i<input.size();i++)
{
char op=input[i]+'0';
if(op=='+'||op=='-'||op=='*'||op=='/')
{
int second=out.top();
out.pop();
int first=out.top();
out.pop();
int result=0;
if(op=='+')
result=first+second;
else if(op=='-')
result=first-second;
else if(op=='*')
result=first*second;
else if(op=='/')
result=first/second+1;
out.push(result);
}
else
{
out.push(input[i]);
}
}
cout<<out.top()<<endl;
return 0;
}