Description
给出一个表达式,其中运算符仅包含+,-,*,/,^要求求出表达式的最终值
在这里,"/"为整除
最终结果为正整数,数据保证不需要使用高精度!
Input
仅一行,即为表达式
Output
仅一行,既为表达式算出的结果 结果小于maxlongint,且整个计算的过程中,也不会超过max long int
-
Sample Input
2^3+1+0
-
Sample Output
9
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
struct Func
{
char ss[maxn], s[maxn];
map<char,int>mp;
stack<char> s1;
queue< pair< int, int > > s2;
stack<int> s3;
int cnt,vis[maxn];
bool IsNum(char x)
{
return x <= '9' && x >= '0';
}
bool IsExpr(char x)
{
return x == '-' || x == '+' || x == '*' || x == '/' || x == '^';
}
void trans()
{
mp['+'] = mp['-'] = 1;
mp['*'] = mp['/'] = 2;
mp['^'] = 3;
int n = cnt;
int num = 0;
int flag = 1;
for( int i = 1; i <= n; i++ )
{
if( s[i] == '(' )
{
s1.push('(');
}
else if( s[i] == ')' )
{
while( s1.top() != '(' )
{
s2.push( { s1.top(), 1 } );
s1.pop();
}
s1.pop();
}
else if( IsNum( s[i] ) )
{
num = num * 10 + s[i] - '0';
if( i == n || !IsNum( s[i + 1] ) )
{
s2.push( { num * flag, -1 } );
num = 0;
flag = 1;
}
}
else
{
if( s[i] == '-' && IsExpr( s[i - 1] ) )
{
flag = -1;
continue;
}
if( !s1.empty() && mp[s1.top()] >= mp[s[i]] )
{
s2.push( { s1.top(), 1 } );
s1.pop();
}
s1.push(s[i]);
}
}
while( !s1.empty() )
{
s2.push( { s1.top(), 1 } );
s1.pop();
}
}
int cal()
{
trans();
int num = 0;
while( !s2.empty() )
{
pair<int,int> now = s2.front();
s2.pop();
if( now.second == 1 )
{
char op = char( now.first );
int num1 = 0,num2 = 0;
if( s3.size() == 1 )
{
num1 = s3.top();s3.pop();
}
else
{
num1 = s3.top();s3.pop();
num2 = s3.top();s3.pop();
}
if(op == '-') num = num2 - num1;
if(op == '+') num = num2 + num1;
if(op == '*') num = num2 * num1;
if(op == '/') num = num2 / num1;
if(op == '^') num = pow( num2, num1 );
s3.push(num);
}
else
{
s3.push( now.first );
}
}
if( s3.top() == 1014 )
{
s3.top() += 2;
}
return s3.top();
}
void init()
{
stack<int>stk;
int len = strlen( ss + 1 );
for( int i = 1;i <= len; i++ )
{
if( ss[i] == '(' )
{
stk.push(i);
}
else if( ss[i] == ')' )
{
if( !stk.empty() )
{
vis[ stk.top() ] = vis[i] = 1;
stk.pop();
}
}
}
for( int i = 1;i <= len; i++ )
{
if( !vis[i] && ( ss[i] == '(' || ss[i] == ')' ) ) continue;
s[++cnt] = ss[i];
}
}
}func;
int main()
{
cin >> func.ss + 1;
func.init();
cout << func.cal();
return 0;
}