高精度加减

#include<bits/stdc++.h>
using namespace std;
struct bignum
{
  int len;
  int num[1000];
  bool b1;
};
void scan(bignum &x,string s)
{
  for(int i=0;i<x.len;i++)
  x.num[x.len-1-i]=s[i]-'0';
}
void print(bignum c)
{
  if(c.b1) printf("-");
  for(int i=c.len;i>=0;i--)
  printf("%d",c.num[i]);
  printf("\n");
}
bignum add(bignum a,bignum b,bignum c)
{
  int i;
  c.len=(a.len>b.len?a.len:b.len);
  for(i=0;i<c.len;i++)
  {
    c.num[i]+=(a.num[i]+b.num[i]);
    if(c.num[i]>=10)
    {
      c.num[i]-=10;
      c.num[i+1]++;
    }
  }
  for(i=c.len;i && !c.num[i];i--);
  c.len=i;
  return c;
}
bignum mnus(bignum a,bignum b,bignum c)
{
  int i,t[1000];
  if(a.len!=b.len)
  {
    c.len=(a.len>b.len?a.len:b.len);
    c.b1=(a.len>b.len?0:1);
  }
  else
  {
    c.len=a.len;
    for(i=a.len-1;i>=0;i--)
    if(a.num[i]!=b.num[i])
      break;
    c.b1=(a.num[i]>b.num[i]?0:1);
  }
  if(c.b1)
  {
    memcpy(t,a.num,sizeof(a.num));
    memcpy(a.num,b.num,sizeof(b.num));
    memcpy(b.num,t,sizeof(t));
  }
  for(i=0;i<c.len;i++)
    if(a.num[i]<b.num[i])
    {
      a.num[i]+=10;
      c.num[i]=a.num[i]-b.num[i];
      a.num[i+1]--;
    }
    else
      c.num[i]=a.num[i]-b.num[i];
  for(i=c.len;i && !c.num[i];i--);
  c.len=i;
  return c;
}
int main()
{
  string s1,s2;
  bignum a,b,c;
  cin>>s1>>s2;
  a.len=s1.size();
  b.len=s2.size();
  memset(a.num,0,sizeof(a.num));
  memset(b.num,0,sizeof(b.num));
  scan(a,s1);
  scan(b,s2);
  print(add(a,b,c));
  print(mnus(a,b,c));
  return 0;
}

上一篇:计算机图形学-几何


下一篇:实战SQL优化之时间从1831s到2.7s的征途