| | | | 描述 Description | | | 给出一个表达式,其中运算符仅包含+,-,*,/,^要求求出表达式的最终值
在这里,"/"为整除
最终结果为正整数,数据保证不需要使用高精度!
| | | |
| | | | 输入格式 Input Format | | | 仅一行,即为表达式
| | | |
| | | | 输出格式 Output Format | | | 仅一行,既为表达式算出的结果 | | | |
| | | | 时间限制 Time Limitation | | | 各个测试点1s
| | | |
|
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<stack>
#include<sstream>
using namespace std;
void pre(string &str)
{
string temp;
for(int i=0;i<str.size();)
{
if(str[i]=='^')
{
int j;
for(j=temp.size()-1;isdigit(temp[j]);j--);j++;
string t(temp.begin()+j,temp.end());
temp.erase(temp.begin()+j,temp.end());
long long x=atoll(t.c_str());
long long cnt=0;
for(i++;i<str.size()&&isdigit(str[i]);i++) cnt=cnt*10+str[i]-'0';
long long val=1;
while(cnt--) val*=x;
t.clear();
ostringstream sout;
sout<<val;
temp+=sout.str();
}
else
{
temp+=str[i];
i++;
}
}
str=temp;
}
void solve(string str)//
{
stack<long long > q;
for(int i=0;i<str.size();)
{
if(isdigit(str[i]))
{
string t;
int flag=0;//0表示正,1表示负
for(int j=i-1;j>=0&&(str[j]=='-'||str[j]=='+');j--)
{
if(str[j]=='-') flag=!flag;
}
while(i<str.size()&&isdigit(str[i])) t+=str[i],i++;
long long x=atoll(t.c_str());
if(!flag) q.push(x);
else q.push(-x);
}
else if(str[i]=='+') i++;
else if(str[i]=='-') i++;
else
{
char ch=str[i];
long long p=q.top();q.pop();
string t;
i++;
int flag=0;//0表示正,1表示负
while(str[i]=='-'||str[i]=='+')
{
if(str[i]=='-') flag=!flag;
i++;
}
while(i<str.size()&&isdigit(str[i])) t+=str[i],i++;
long long x=atoll(t.c_str());
if(flag) x=-x;
if(ch=='*') p*=x;
else p/=x;
q.push(p);
}
}
long long cnt=0;
while(!q.empty())
{
cnt+=q.top();
q.pop();
}
cout<<cnt<<endl;
}
int main()
{
string str;
while(cin>>str)
{
pre(str);
solve(str);
//cout<<str<<endl;
}
return 0;
}
//45525233423*7