c语言两个大数相加

 

 

void AddTwoBigNumbers(char bigN[], char bigM[], char sum[])
{
    int i=strlen(bigM)-1, j=strlen(bigN)-1, k, carry=0;
    for(k=0; i>=0 && j>=0; --i, --j, ++k)
    {
        sum[k] = (bigM[i]-'0' + bigN[j]-'0' + carry)%10 + '0';
        carry = (bigM[i]-'0' + bigN[j]-'0' + carry)/10;
    }

    for(; i>=0; --i, ++k)
    {
        sum[k] = (bigM[i]-'0' + carry)%10 + '0'; 
        carry = (bigM[i]-'0' + carry)/10;
    }
    for(; j>=0; --j, ++k)
    {
        sum[k] = (bigN[j]-'0' + carry)%10 + '0'; 
        carry = (bigN[j]-'0' + carry)/10;
    }
    if(carry!=0)
    {
        sum[k++]=carry+'0';
    }
    sum[k]=0;

    //Reversing string
    for(int t=0; t<n/2; ++t)
    {
        char temp=sum[t];
        sum[t]=sum[n-1-t];
        sum[n-1-t]=temp;
    }
}

 

copy from:https://stackoverflow.com/questions/55490065/how-do-i-add-two-large-non-negative-integers-using-char-array-in-c

posted @ 2020-07-06 08:38  wolbo  阅读(432)  评论(0编辑  收藏  举报