C按字符数组加两个大数

时间:2019-03-30 11:06:48

标签: c

我需要使用char数组添加两个大数字,大小为0-100位,我不知道该如何处理空数组单元格。

如何比较未分配编号的数组单元格。我想将案件分为两部分。

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

1 个答案:

答案 0 :(得分:0)

每个数组都可以使用一个计数器。
当计数器到达数组末尾时,该if块将不再执行。
当两个计数器都到达数组末尾时,请跳出循环。

//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