任意长度正整数相加

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>

char* addBigInt(char* num1,char* num2)
{
    int c=0;//保存进位
    int i=strlen(num1)-1;
    int j=strlen(num2)-1;
    int maxLength=(strlen(num1))>=(strlen(num2))?(strlen(num1)+1):(strlen(num2)+1);    
     char *rst=(char*)malloc(maxLength+1);
     if(rst==NULL)
     {
         printf("malloc error!\n");
         exit(1);
     }
     
     rst[maxLength]='\0';
     int k=maxLength-1;
         printf("k=%d\n",k);
     while((i>=0)&&(j>=0))
     {
         rst[k]=((num1[i]-'0')+(num2[j]-'0')+c)%10+'0';
         c=((num1[i]-'0')+(num2[j]-'0')+c)/10;
         i--;j--;k--;
         printf("rst[%d]=%s\n",k,rst);
     }
     
     while(i>=0)
     {
         rst[k]=((num1[i]-'0')+c)%10+'0';
         c=((num1[i]-'0')+c)/10;
         i--;k--;
     }
     
     while(j>=0)
     {
         rst[k]=((num2[j]-'0')+c)%10+'0';
         c=((num2[j]-'0')+c)/10;
         j--;k--;
     }
     
     rst[0]=c+'0';
     
     if(rst[0]!='0')
     {
         return rst;
     }else{
         return rst+1;//指针右移一单位 
     }
}
     
     int main()
     {
         char num1[]="123456789323";
         char num2[]="45671254563123";
         char *result=NULL;
         
         result=addBigInt(num1,num2);
         printf("%s+%s=%s\n",num1,num2,result);
         
         return 0;
     }

 

posted @ 2017-01-11 11:36  邹大佳  阅读(325)  评论(0编辑  收藏  举报