给定一个只包含加法和乘法的算术表达式,请你编程计算表达式的值。
输入格式:
每组输入数据仅有一行,为需要你计算的表达式,表达式中只包含数字、加法运算符“+”和乘法运算符“*”,且没有括号,所有参与运算的数字均为0到231-1之间的整数。输入数据保证这一行只有0~9、+、*这12种字符。
数据规模:
对于30%的数据,0≤表达式中加法运算符和乘法运算符的总数≤100;
对于80%的数据,0≤表达式中加法运算符和乘法运算符的总数≤1000;
对于100%的数据,0≤表达式中加法运算符和乘法运算符的总数≤100000。
输出格式:
每组输出只有一行,包含一个整数,表示这个表达式的值。注意:当答案长度多于4位时,请只输出最后4位,前导0不输出。
下面是对样例数据的解释:
样例1计算的结果为8,直接输出8。
样例2计算的结果为1234567891,输出后4位,即7891。
样例3计算的结果为1000000004,输出后4位,即4。
限制:
空间限制:128MByte 时间限制:1秒
样例:
输入: 1+1*3+4 1+1234567890*1 1+1000000003*1
输出: 8 7891 4
算法思想
定义两个栈:
数据栈:s1,用以存储数字;
运算符栈:s2,用以存储运算符;
将字符元素一个个扫描,遇到操作数则进栈s1,
遇到运算符型,需要判断:
s2栈顶元素运算符优先级是否比当前运算符大或等于:
1. 成立:
1.1 那么s2栈顶运算符出栈:假设出栈是运算符a,那么此时从s1中出栈两个数字b、c参与运算,把运算结果进栈s1;
1.2 循环1.1操作,直到栈顶元素不满足条件
1.3 当前运算符入栈
2. 不成立:当前运算符入栈
遇到(直接进s1,
遇到)则就要把这一对括号之间运算符都一个个拿出来运算,与1.1处理过程一致
#include <bits/stdc++.h>
using namespace std;
int cuclt(int x,int y,char c)
{
int result = 0;
if(c == '*')
{
result = (x % 10000) * (y % 10000) % 10000;
}
else if(c == '/')
{
result = (x % 10000) / (y % 10000);
}
else if(c == '+')
{
result = ((x % 10000) + (y % 10000))%10000;
}
else if(c == '-')
{
result = (x % 10000) - (y % 10000);
}
return result;
}
char bds[1000000];
int main()
{
stack<int> s1;
stack<int> s2;
map<int,int> m;
m['+'] = 1;
m['-'] = 1;
m['*'] = 2;
m['/'] = 2;
m['('] = 0;
cin >> bds;
int len = strlen(bds);
int i = 0;
while(i < len)
{
if(bds[i] >= '0' && bds[i] <= '9')
{
int num = 0;
while (bds[i] >= '0' && bds[i] <= '9')
{
num = num * 10 + bds[i] -'0';
i++;
}
s1.push(num);
}
else
{
if(bds[i] == '(')
{
s2.push(bds[i]);
}
else if(bds[i] == ')')
{
while(s2.top() != '(')
{
int czs = s2.top();
s2.pop();
int x = s1.top();
s1.pop();
int y = s1.top();
s1.pop();
s1.push(cuclt(y,x,czs));
}
s2.pop();
}
else
{
while(s2.size() > 0 && m[s2.top()] >= m[bds[i]])
{
int czs = s2.top();
s2.pop();
int x = s1.top();
s1.pop();
int y = s1.top();
s1.pop();
s1.push(cuclt(y,x,czs));
}
s2.push(bds[i]);
}
i++;
}
}
while (s2.size())
{
int czs = s2.top();
s2.pop();
int x = s1.top();
s1.pop();
int y = s1.top();
s1.pop();
s1.push(cuclt(y,x,czs));
}
cout << s1.top() % 10000;
return 0;
}