| | | | 描述 Description | | | 给出一个表达式,其中运算符仅包含+,-,要求求出表达式的最终值
保证数据中不会出现负数。
| | | |
| | | | 输入格式 Input Format | | | 仅一行,即为表达式
| | | |
| | | | 输出格式 Output Format | | | 仅一行,既为表达式算出的结果 | | | |
| | | | 时间限制 Time Limitation | | | 各个测试点1s
| | | |
| | | | 注释 Hint | | | 表达式总长度<=255 表达式中数字位数<=255 | |
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cctype>
using namespace std;
const int maxn=300;
class bignum
{
int num[maxn+1];
public:
bignum(){memset(num,0,sizeof(bignum));}
friend bignum operator +(bignum &a,bignum &b);
friend bignum operator -(bignum &a,bignum &b);
friend ostream &operator <<(ostream & cout,const bignum &a);
bignum & operator =(string str);
};
bignum operator -(bignum &a,bignum &b)
{
bignum temp;
for(int i=maxn;i>=0;i--)
{
temp.num[i]=a.num[i]-b.num[i];
}
for(int i=maxn;i>=0;i--)
{
if(temp.num[i]<0)
{
temp.num[i]+=10;
temp.num[i-1]--;
}
}
return temp;
}
ostream &operator <<(ostream & cout,const bignum &a)
{
for(int i=0,flag=0;i<maxn+1;i++)
{
if(i==maxn||flag||a.num[i])
{
cout<<a.num[i];flag=1;
}
}
return cout;
}
bignum & bignum::operator =(string str)
{
memset(num,0,sizeof(num));
int i=maxn,j=str.size();
for(j--;j>=0;j--) num[i--]=str[j]-'0';
}
bignum operator +(bignum &a,bignum &b)
{
bignum temp;
int t=0;
for(int i=maxn;i>=0;i--)
{
temp.num[i]=a.num[i]+b.num[i]+t;
t=temp.num[i]/10;
temp.num[i]%=10;
}
return temp;
}
int main()
{
string str;
getline(cin,str);
bignum cnt;
string temp;
bignum t;
int flag=1;
for(int i=0;i<str.size();)
{
if(str[i]=='+') flag=1,i++;
else if(str[i]=='-')flag=2,i++;
else if(isdigit(str[i]))
{
while(i<str.size()&&isdigit(str[i]))
{
temp+=str[i];
i++;
}
t=temp;temp.clear();
if(flag==1)cnt=cnt+t;
else if(flag==2) cnt=cnt-t;
}
}
cout<<cnt<<endl;
return 0;
}