ACM--大数减法

#include<string>
#include<fstream>
using namespace std;
ifstream fin("input.txt");
ofstream fout("out.txt");
string xjianfa(string s1,string s2);
string xjiafa(string s1,string s2);
string jianfa(string s1,string s2);
int max(string s1,string s2);
string clear(string s);
string nag = "";

void main()
{
 int ii=0;
 bool isnum=true;
 string a,b;
 fin>>a;
 fin>>b;
 while(ii<a.length()){
  if(a[ii]>'9' || a[ii]<'0'){
   fout<<"Wrong Input!";
   isnum = false;
   break;
  }
  ii++;
 }
 ii = 0;
 while(ii<b.length()){
  if(b[ii]>'9' || b[ii]<'0'){
   fout<<"Wrong Input!";
   isnum = false;
   break;
  }
  ii++;
 }
 if (isnum)
  fout<<jianfa(a,b);
}
string jianfa(string s1,string s2){
 string result;
 if(s1[0]=='-'){
  if (s2[0]=='-'){
   s1 = s1.substr(1,s1.length()-1);
   s2 = s2.substr(1,s2.length()-1);
   result = xjianfa(s2,s1);
  }
  else{
   s1 = s1.substr(1,s1.length()-1);
   result = "-" + xjiafa(s1,s2);
  }
 }
 else{
  if (s2[0]=='-'){
   if (s2[0]=='-') s2 = s2.substr(1,s2.length()-1);
   result = xjiafa(s1,s2);
  }
  else result = xjianfa(s1,s2);
 }
 return result;
}

string xjianfa(string s1,string s2)
{
 string tmp;
 while (s1.length() < s2.length()){
  s1='0'+s1;
  nag = "-";
 }
 while (s2.length() < s1.length())
  s2='0'+s2;
 if (max(s1,s2)==1){
  tmp = s1;s1 = s2;s2 =tmp;
  nag = '-';
 }
 else
  if (max(s1,s2)==2)
   return "0";

 for (int i=0;i<s1.length();i++){
  if ((int)s1[i] >= (int)s2[i]){
   s1[i] = (s1[i]-s2[i])+'0';
  }
  else{
   s1[i] = s1[i]+10-s2[i]+'0';
   int k=1;
   while (s1[i-k]=='0')
    s1[i-k++]='9';
   s1[i-k] = s1[i-k]-1;
  }
 }
 return clear(nag+s1);
}

string xjiafa(string s1,string s2){
 nag = "";
 while (s1.length()<s2.length())
  s1='0'+s1;
 while (s1.length()>s2.length())
  s2='0'+s2;
 s1='0'+s1;
 s2='0'+s2;
 for (int i=(s1.length()-1);i>0;i--){
  s1[i] = s1[i]+s2[i]-'0';
  if(s1[i]>'9'){
   s1[i-1] = s1[i-1] + 1;
   int k=1;
   while (s1[i-k]=='9'+1){
    s1[i-k] = '0';
    s1[i-k++] = s1[i-k++] + 1;
   }
   s1[i] = s1[i] - 10;
  }
 }
 return clear(s1);
}

string clear(string s){
 if (s.length()==0)
  s="0";
 if (s[0]=='-')
  s = s.substr(1,(s.length()-1));
 while (s.length()>0 && s[0]=='0')
  s = s.substr(1,(s.length()-1));
 if (s.length()==0)
  s="0";
 return nag+s;
}

int max(string s1,string s2){
 int i=0,t=2;
 while (i<s1.length()){
  if(s1[i]>s2[i]){
   t = 0;
   break;
  }
  else
   if (s1[i]<s2[i]){
    t = 1;
    break;
   }
   else
    i++;
 }
 return t;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值