首页 > 其他 > 详细

大数相加

时间:2019-04-11 16:31:11      阅读:133      评论:0      收藏:0      [点我收藏+]

一:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm> 
using namespace std;
int compare(string str1,string str2)
{
    if(str1.length()>str2.length()) return 1;
    else if(str1.length()<str2.length())  return -1;
    else return str1.compare(str2);
}
string xj(string s1,string s2)
{
    string s;
    int len1=s1.length();
    int len2=s2.length();
    if(len1<len2){
        for(int i=1;i<=len2-len1;i++)
          s1="0"+s1;
    }
    else{
        for(int i=1;i<=len1-len2;i++)
          s2="0"+s2; 
    }
    len1=s1.length();
    int x=0,t;
    for(int i=len1-1;i>=0;i--){
        t=s1[i]-0+s2[i]-0+x;
        x=t/10;
        t%=10;
        s=char(t+0)+s;
    }
    if(x!=0)
      s=char(x+0)+s;
    return s;
}
int main()
{
    int n,i;
    cin>>n;
    for(i=0;i<n;i++)
    {
    string s1,s2;
    cin>>s1>>s2;
    cout<<"Case "<<i+1<<":"<<endl;
    cout<<s1<<" + "<<s2<<" = "<<xj(s1,s2)<<endl;
    if(i!=n-1)
        printf("\n");
    } 
    return 0;
}

二:

#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 1000+10;
int main(void)
{
    int n[maxn],m[maxn],c[maxn];
    char a[maxn],b[maxn];
    int s1,s2,x,s3;
    int i,j,k,g,t;
    scanf("%d",&t);
    for(i=0;i<t;i++)
    {
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        memset(c,0,sizeof(c));
        memset(n,0,sizeof(n));
        memset(m,0,sizeof(m));
        cin>>a>>b;
        printf("Case %d:\n",i+1);
        s1=strlen(a);
        s2=strlen(b);
        for(j=0;j<s1;j++)
           n[s1-j]=a[j]-0;
        for(k=0;k<s2;k++)
           m[s2-k]=b[k]-0;
        s3=1;
        x=0;
        while(s3<=s1||s3<=s2)
        {
             c[s3]=n[s3]+m[s3]+x;
             x=c[s3]/10;
             c[s3]%=10;
             s3++;
        }
        c[s3]=x;
        while(c[s3]==0)
        {
            s3--;
        }
        cout<<a;
        printf(" + ");
        cout<<b;
        printf(" = ");
        for(g=s3;g>=1;g--)
        {
            printf("%d",c[g]);
        }
        printf("\n");
        if(i!=t-1)
            printf("\n"); 
    } 
    return 0;
} 

 

大数相加

原文:https://www.cnblogs.com/ylrwj/p/10690411.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!