题目描述
给出一个表达式,其中运算符仅包含+,-,*,/,^(加 减 乘 整除 乘方)要求求出表达式的最终值。
数据可能会出现括号情况,还有可能出现多余括号情况。
数据保证不会出现大于或等于231的答案。
数据可能会出现负数情况。
输入格式
输入仅一行,即为表达式。
输出格式
输出仅一行,既为表达式算出的结果。
输入样例:
(2+2)^(1+1)
输出样例:
16
题解
- 从前往后扫描字符串。维护两个栈,一个数字栈,储存数字。一个运算符栈,储存运算符。
- 如果是数字就压入数字栈中。
- 如果是‘(’ 就压入运算符栈中。
- 如果是‘ )’ 就结算整个括号,并且删除从运算符栈中删除‘(’。
- 如果是 ‘+’ 或‘ - ’或‘ * ’ 或‘ / ’ 或乘方,就结算前面优先级高或等于当前运算符。
代码
#include <iostream>
#include <stack>
#include <string>
using namespace std;
stack<int> nums;
stack<char> ops;
//快速幂
int qmi(int a, int b)
{
int res = 1;
while(b)
{
if(b & 1) res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
//计算
void cal()
{
int a = nums.top(); nums.pop();
int b = nums.top(); nums.pop();
char c = ops.top(); ops.pop();
int d;
if(c == '+') d = a + b;
else if(c == '-') d = b - a;
else if(c == '*') d = b * a;
else if(c == '/') d = b / a;
else d = qmi(b, a);
nums.push(d);
}
int main()
{
string str;
cin >> str;
if(str[0] == '0') str = '0' + str; //-(1 + 1)
string left;
for(int i = 0; i < str.size(); i++) left += "(";
str = left + str + ")"; //保证左括号数量大于右括号
for(int i = 0; i < str.size(); i++)
{
if(str[i] >= '0' && str[i] <= '9')
{
int j = i, t = 0; //多位数字
while(j < str.size() && str[j] >= '0' && str[j] <= '9')
{
t = t * 10 + str[j] - '0';
j++;
}
i = j - 1;
nums.push(t);
}
else
{
char c = str[i];
if(c == '(') ops.push(c);
else if(c == '+' || c == '-')
{
if(c == '-' && i && !(str[i - 1] >= '0' && str[i - 1] <= '9') && str[i - 1] != ')') //'-' 代表负号
{
if(str[i + 1] == '(') // 将-(...)变成-1 * (...)
{
nums.push(-1);
ops.push('*');
}
else
{
int j = i + 1, t = 0;
while(j < str.size() && str[j] >= '0' && str[j] <= '9')
{
t = t * 10 + str[j] - '0';
j++;
}
nums.push(-t);
i = j - 1;
}
}
else //将 + - 号前面的运算符优先级高的结算,加,减优先级最低。前面都可以结算
{
while(ops.top() != '(') cal();
ops.push(c);
}
}
else if(c == '*' || c == '/')将 * / 号前面的运算符优先级高或等于的结算
{
while(ops.top() == '*' || ops.top() == '/' || ops.top() == '^') cal();
ops.push(c);
}
else if(c == '^') 将 '^' 号前面的运算符优先级高或等于的结算
{
while(ops.top() == '^') cal();
ops.push(c);
}
else if(c == ')') // 将整个括号结算
{
while (ops.top() != '(') cal();
ops.pop(); //删除'('
}
else cout << "invalid operator!" << endl;
}
}
cout << nums.top() << endl;
return 0;
}