#include <iostream>
#include <string>
#include <cstring>
#include <stack>
using namespace std;
stack<int> opnd;
stack<char> optr;
bool IsOptr(char c)
{
string optr = "+*-/()";
if(optr.find(c) == string::npos)
return false;
return true;
}
char Compare (char a, char b)
{
if(a == '+' || a == '-')
{
if(b == '*'|| b == '/' || b == '(')
{
return '<';
}
else
return '>';
}
else if(a == '*' || a == '/')
{
if(b == '(')
return '<';
else
return '>';
}
else if(a == '(')
{
if(b == ')')
return '=';
else
return '<';
}
}
int Calculation(char op, int a, int b)
{
switch(op)
{
case '+':
return a + b;
break;
case '-':
return a - b;
break;
case '*':
return a * b;
break;
case '/':
return a / b;
}
}
int EvaluateExpression(char* exp, int len)
{
int i = 0;
int ans = 0;
while(i < len)
{
if(!IsOptr(exp[i]))
{
int sum = 0;
while(!IsOptr(exp[i]) && i < len)
{
sum = sum*10 + exp[i] - '0';
++i;
}
opnd.push(sum);
}
else
{
char com = '<';
if(optr.size() != 0)
com = Compare(optr.top(), exp[i]);
switch (com)
{
case '<':
optr.push(exp[i]);
++i;
break;
case '=':
optr.pop();
++i;
break;
case '>':
char cal = optr.top();
optr.pop();
int a = opnd.top(); opnd.pop();
int b = opnd.top(); opnd.pop();
int temp = Calculation(cal, a, b);
opnd.push(temp);
}
}
}
while(optr.size() != 0)
{
char cal = optr.top();
optr.pop();
int a = opnd.top(); opnd.pop();
int b = opnd.top(); opnd.pop();
int temp = Calculation(cal, a, b);
opnd.push(temp);
}
ans = opnd.top();
return ans;
}
int main(void)
{
string Input;
cin>>Input;
int len = Input.size();
char* expression = const_cast<char*>(Input.c_str());
cout<<EvaluateExpression(expression, len);
return 0;
}
华为题目(四则运算)
最新推荐文章于 2020-08-12 11:59:14 发布