How do I add two big integers, I have tried using arrays and it still has some bugs. Ex: A 23 digit + 25 digit positive integer (2345235... + 34634235....)
I've tried using arrays to separate the digits and eventually add them up, but there is still some bugs, like when 999 + 999, it will output 998, or when it is 24 digits + 25 digits, the code becomes complicated. Is there any easy way of doing it?
#include <stdio.h>
int main(void)
{
int length_A, length_B, times;
long long int A[101] = {0};
long long int B[101] = {0};
long long int total[101] = {0};
scanf("%d", &length_A);
for (int i = 0; i < length_A; i++)
{
scanf("%1lld", &A[i]);
}
scanf("%d", &length_B);
for (int j = 0; j < length_B; j++)
{
scanf("%1lld", &B[j]);
}
if (length_A > length_B)
{
times = length_A - length_B;
for (int l = 0; l < times; l++)
{
total[l] = A[l];
}
for (int k = 0; k < length_B; k++)
{
total[k+times] = A[k+times] + B[k];
if(total[k+times] > 9)
{
if (total[k+times-1] == 9)
{
total[k+times-2]++;
total[k+times-1] = 0;
total[k+times] -= 10;
}
else if (total[k+times-1] < 9)
{
total[k+times-1]++;
total[k] -= 10;
}
}
}
for (int z = 0; z < length_B; z++)
{
printf("%lld", total[z]);
}
}
else if (length_B > length_A)
{
times = length_B - length_A;
for (int k = 0; k < length_B; k++)
{
for (int l = 0; l < times; l++)
{
total[l] = B[l];
}
total[k+times] = A[k] + B[k+times];
if(total[k] > 9)
{
if (total[k-times] == 9)
{
total[k-times-1]++;
total[k-times] = 0;
total[k] -= 10;
}
else
{
total[k-1]++;
total[k] -= 10;
}
}
}
for (int z = 0; z < length_B; z++)
{
printf("%lld", total[z]);
}
}
else
{
for (int k = 0; k < length_B; k++)
{
total[k] = A[k] + B[k];
if(total[k] > 9)
{
if (total[k-1] == 9)
{
total[k-2]++;
total[k-1] = 0;
total[k] -= 10;
}
else
{
total[k-1]++;
total[k] -= 10;
}
}
}
for (int z = 0; z < length_B; z++)
{
printf("%lld", total[z]);
}
}
}
total[-1] = ....The
totalarray should be 1 longer thanA,Bto handle the potential last "carry".long long int A[101] = {0};is excessive.signed char A[101] = {0};is sufficient to save all 1 and 2 decimal digit values.Maybe, easy for some, a challenge for learners.
A key strategy is divide and conquer.
Consider separating input from addition and output.
Form 3 functions.
Then form
main()