#pragma once
#include <string>
class Calculator {
public:
bool Exec(const std::string& strInput, int& result);
private:
bool IsNumber(char c);
bool IsOperator(char c);
int GetPriority(char c);
};
#include "Calculator.h"
#include <stack>
using namespace std;
bool Calculator::IsNumber(char c) {
return (c >= '0' && c <= '9');
}
bool Calculator::IsOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')');
}
int Calculator::GetPriority(char c) {
switch (c)
{
case '+':
case '-':
{
return 1;
}
case '*':
case '/':
{
return 2;
}
default:
return 0;
}
}
bool Calculator::Exec(const string& strInput, int& result)
{
int index = 0;
int len = strInput.length();
//有效性检查
while (index < len)
{
if (!IsNumber(strInput[index]) && !IsOperator(strInput[index]))
return false;
else
index++;
}
//中缀表达式转为后缀表达式
stack<char> operatorStack;
string strOutput;
index = 0;
len = strInput.length();
while (index < len)
{
if (IsNumber(strInput[index]))
{
do
{
strOutput += strInput[index++];
} while (index < len && IsNumber(strInput[index]));
strOutput += ' ';
}
else if (strInput[index] == '(')
{
operatorStack.push(strInput[index++]);
}
else if (strInput[index] == ')')
{
while (!operatorStack.empty())
{//弹出直到遇到左括号
char last = operatorStack.top();
operatorStack.pop();
if (last == '(')
break;
else
strOutput += last;
}
index++;
}
else
{
if (operatorStack.empty())
{//栈为空,压入
operatorStack.push(strInput[index]);
}
else
{
while (!operatorStack.empty() && GetPriority(strInput[index]) <= GetPriority(operatorStack.top()))
{//优先级比栈顶元素小,则弹出(符合优先级和从左到右计算规则)
strOutput += operatorStack.top();
operatorStack.pop();
}
operatorStack.push(strInput[index]);
}
index++;
}
}
//弹出剩余的元素
while (!operatorStack.empty())
{
strOutput += operatorStack.top();
operatorStack.pop();
}
//计算结果
stack<int> resultStack;
string strTemp;
index = 0;
len = strOutput.length();
while (index < len)
{
if (IsNumber(strOutput[index]))
{
strTemp.clear();
do
{
strTemp += strOutput[index++];
} while (index < len && strOutput[index] != ' ');
resultStack.push(atoi(strTemp.c_str()));
}
else
{
int number1 = 0;
int number2 = 0;
if (resultStack.size() >= 2)
{
number1 = resultStack.top();
resultStack.pop();
}
else if (strOutput[index] == '+' || strOutput[index] == '-')
{//兼容正负数表示法,-1=0-1
number1 = 0;
}
else
{
return false;
}
number2 = resultStack.top();
resultStack.pop();
if (strOutput[index] == '+')
resultStack.push(number1 + number2);
else if (strOutput[index] == '-')
resultStack.push(number1 - number2);
else if (strOutput[index] == '*')
resultStack.push(number1 * number2);
else if (strOutput[index] == '/')
resultStack.push(number1 / number2);
}
index++;
}
if (resultStack.empty())
{
return false;
}
else
{
result = resultStack.top();
return true;
}
}