Poj1503(高精度加法)

带前导0的高精度加法

题目大意

就是n个数做加法

高精度

翻过来做,然后在string转num数组的时候忽略掉前导零

CODE

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>

#define LEN 4095

inline int max(int a, int b) { return a > b ? a : b; }
inline int min(int a, int b) { return a < b ? a : b; }

void outp(int arr[])
{
    int i;
    for (i = 0; arr[i] != -1; i++)
    {
        printf("%d", arr[i]);
    }
    printf("\n");
}

void init_num_arr(int arr[])
{
    for (int i = 0; i < LEN; i++) { arr[i] = 0; }
}

int num_len(int arr[])
{
    int i;
    for (i = 0; arr[i] != -1; i++) { ; }
    return i;
}

void str_to_num(char str[], int num[])
{
    int length = strlen(str);
    for (int i = 0; i < length; i++)
    {
        num[i] = str[i] - 48;
    }
    num[length] = -1;
}

void exchange(int num[], int arr[])
{
    int n = num_len(num);
    for (int i = 0; i < n; i++)
    {
        arr[n - i - 1] = num[i];
    }
    arr[n] = -1;
}

void high_plus(int numA[], int numB[], int ans[])
{
    int a[LEN], b[LEN];
    init_num_arr(a);
    init_num_arr(b);
    exchange(numA, a);
    exchange(numB, b);
    int lenA = num_len(a); 
    int lenB = num_len(b);
    a[lenA] = 0;
    b[lenB] = 0;
    for (int i = 0; i < lenA; i++)
    {
        a[i] += b[i];
        a[i + 1] += a[i] / 10;
        a[i]     %= 10;
    }
    if (a[lenA]) { lenA++; }

    a[lenA] = -1;
    b[lenA] = -1;
    exchange(a, ans);
    ans[lenA] = -1;
}

int main(void)
{
    int numA[LEN], numB[LEN], ans[LEN];
    char strA[LEN], strB[LEN];
    init_num_arr(numA);
    init_num_arr(numB);
    init_num_arr(ans);
    ans[1] = -1;
    while (scanf("%s", strA) == 1)
    {
        if (48 == strA[0] && 1 == strlen(strA)) { break; }
        int zero;
        for (zero = 0; zero < strlen(strA); zero++)
        {
            if (strA[zero] != 48) { break; }
        }
        str_to_num(strA + zero, numA);
        for (int i = 0; i < num_len(ans); i++)
        {
            numB[i] = ans[i];
        }
        numB[num_len(ans)] = -1;
        if (num_len(numA) > num_len(numB))
        {
            high_plus(numA, numB, ans);
            continue;
        }
        high_plus(numB, numA, ans);
    }

    outp(ans);
    return 0;
}

你可能感兴趣的:(poj)