简体   繁体   English

C通过char数组添加两个大数字

[英]C Adding two big number by char array

I need to add two big number sized 0-100 digits with char array and i dont know how can i deal with the empty array cell.. 我需要添加两个大数字大小的0-100位数字与char数组,我不知道我怎么能处理空数组单元格..

How can i compare the cell of array with unassigned number. 如何比较数组的单元格与未分配的数字。 i want to divide the case into two part. 我想把案件分成两部分。

bigM[i] == empty cell, directly put bigN[i] + carry in to sum[i] 
bigN[i] == empty cell, directly put bigM[i] + carry  in to sum[i]

//
// AddTwoBigNumbers: to sum up two big numbers represented as digits in a char clear_char_array
//
// input:  char bigN[], char bigM[]:  two large numbers
// output the sum as a big number in the input array char sum[]
void AddTwoBigNumbers(char bigN[], char bigM[], char sum[])
{
    reverseArray(bigN, 0, 100);
    reverseArray(bigM, 0, 100);

    //calculation
    int carry = 0;
    for(int i = 100; i >= 0; i--)
    {
        int sum_two = (bigN[i] - '0') + (bigM[i] - '0') + carry;
        sum[i] = sum_two % 10 + '0';
        carry = sum_two / 10;
    }

    reverseArray(sum, 0, 100);
}

ideone link 意想不到的联系

A counter for each array could be used. 可以使用每个阵列的计数器。
When a counter reaches the end of an array, that if block will no longer execute. 当计数器到达数组的末尾时, if块将不再执行。
When both counters reach the end of the array, break out of the loop. 当两个计数器都到达数组的末尾时,请退出循环。

//calculation
int i = 0;
int carry = 0;
int index = 0;
int next = 0;
while ( 1) {
    int sum_two = carry;
    if ( bigM[index]) {// not zero
        sum_two += bigM[index] - '0';
        index++
    }
    if ( bigN[next]) {//not zero
        sum_two += bigN[next] - '0';
        next++;
    }
    sum[i] = sum_two % 10 + '0';
    i++;
    carry = sum_two / 10;
    if ( bigM[index] == 0 && bigN[next] == 0) {//both are zero
        break;
    }
}
if ( carry) {
    sum[i] = carry + '0';
    i++;
}
sum[i] = 0;//terminate with zero

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM