ZOJ 1292 大数相加

这是我自己写的大数相加的代码,看起来有些长,不过胜在好理解。。。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void reverse(char *s)    
{
    int i,j,len;
    char temp;
    len=strlen(s);
    for(i=0,j=len-1;i<j;j--,i++){
        temp=s[i];
        s[i]=s[j];
        s[j]=temp;                        
    }    
}

int CTN(char c){  // 字符转化为数字
    int n;
    if(c>='0' && c<='9')  n=c-'0';
    else if(c>='a' && c<='j')  n=c-'a'+10;
    return n;
}
char NTC(char n){
    char ch;
    if(n>=0 && n<=9)  ch=n+'0';   // 数字转化为字符
    else if(n>=10 && n<20)  ch=n+'a'-10;
    return ch;
}
int main()
{
    int i,j,len1,len2,l,c,n;
    char s1[105],s2[105];
    int m[105];
    scanf("%d",&n);
    memset(s1,0,sizeof(s1));
    while(n--){
        scanf("%s",s1);
        len1=strlen(s1);
        reverse(s1);
        memset(m,0,sizeof(m));
        for(i=0;i<len1;i++) 
            m[i]=CTN(s1[i]);
        memset(s2,0,sizeof(s2));
        while(scanf("%s",s2) && strcmp(s2,"0")){
            len1=strlen(s1);
            len2=strlen(s2);
            reverse(s2);
            l=len1>len2?len1:len2;
            for(i=0,c=0;i<l||c;i++ )
            {
               if( i<len1)
                  c+=m[i];
               if( i<len2 )
                  c+=CTN(s2[i]);
               m[i]=c%10;
               c/=10;
               s1[i]=NTC(m[i]);
            }
            memset(s2,0,sizeof(s2));
        }
        while(!m[i]){
              --i;
              if(i<0) {printf("0"); break;}
        }
       
        for( ;i>=0;i--){
             s1[i]=NTC(m[i]);
             printf("%c",s1[i]);
        }
        printf("\n");
        if(n)  printf("\n");
    }
    //system("pause");
    return 0;   
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值