从左至右加2个大数字

时间:2019-05-12 14:36:41

标签: c c99

是否可以在不反转数组的情况下添加2个大数字? 我必须使用此函数声明:

int add(const char* n1, const char* n2, char** sum);

我无法反转数组,因为它是cosnt char*:(

1 个答案:

答案 0 :(得分:0)

这是一个挑战-以下代码从左到右添加了两个非负数字符串。它只需要较长的时间,直到数字对齐,然后逐个字符地添加。如果有一个进位,它将从右向左传播,以固定已经累加的数字:

   ******************************************************************************
    * The Google Mobile Ads SDK was initialized incorrectly. AdMob publishers    *
    * should follow the instructions here: Link to add a valid  *
    * App ID inside the AndroidManifest. Google Ad Manager publishers should     *
    * follow instructions here: Link.                           *
    ******************************************************************************


        at com.google.android.gms.internal.ads.zzabg.attachInfo(Unknown Source:16)
        at com.google.android.gms.ads.MobileAdsInitProvider.attachInfo(Unknown Source:3)
        at android.app.ActivityThread.installProvider(ActivityThread.java:6724)
            ... 10 more

输出

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

int add(const char *n1, const char *n2, char **sum) {
    const char *longer = n1, *shorter = n2; // ['1', '2', '3'] + ['8', '9']
    size_t bigger = strlen(longer), smaller = strlen(shorter); // 3, 2

    if (smaller > bigger) {
        shorter = n1;
        longer = n2;

        size_t temporary = smaller;
        smaller = bigger;
        bigger = temporary;
    }

    *sum = malloc(bigger + 2); // 3 + carry + null byte
    (*sum)[0] = '0';
    (*sum)[bigger + 1] = '\0'; // ['0', x, x, x, '\0']

    for (int power_of_ten = bigger; power_of_ten > 0; power_of_ten--) { // 3 ... 1 (for length comparison)
        size_t idx = bigger - power_of_ten; // 0 ... 2 (for indexing left to right)

        if (power_of_ten > smaller) {
            (*sum)[idx + 1] = longer[idx]; // just copy from longer to sum
        } else {
            char c = shorter[idx - (bigger - smaller)] + longer[idx] - '0'; // add
            (*sum)[idx + 1] = c;

            for (int j = idx + 1; j > 0 && (*sum)[j] > '9'; j--) { // backward carry
                (*sum)[j] -= 10;
                (*sum)[j - 1] += 1;
            }
        }
    }

    if ((*sum)[0] == '0') { // ['0', '2', '1', '2'] -> ['2', '1', '2']
        for (int j = 0; j < bigger + 1; j++) {
            (*sum)[j] = (*sum)[j + 1];
        }
    }

    return 42; // problem didn't specify what `int add(...)` returns
}

int main() {
    char a[] = "509843702", b[] = "430958709432";
    char *s;

    (void) add(a, b, &s);

    printf("%s\n", s);

    (void) free(s);

    return 1;
}

检查

> ./a.out
431468553134
>

此加法涉及五个进位,其中三个是独立的(不是级联)。