求n个大数字的和

Finding the sum of n big numbers

本文关键字:数字      更新时间:2023-10-16

问题:给定一个数字k,求k个正大整数的和。"这是我的代码,它有效,但我们的在线法官拒绝了它,"segfault说。为什么显示segfault?我可以用两根绳子做,但为什么不起作用?

#include <iostream>
#include <string.h>
using namespace std;
void add(int l,int k);
void append(char a[], int temp);
int o;
int tf=0;
int carry=0;
char b[1000000];
char a[10000][10000];
char c[1000000];
int main()
{
    int k,x=0,l=0,m=0;
    cin>>k;
    while(x<k)
    {
        cin>>a[x];
        if(strlen(a[x])>l)
        {
            l=strlen(a[x]);
        }
        x++;
    }
    x=0;
    while(x<k)
    {
        if(strlen(a[x])<l)
        {
            int temp=0;
            append(a[x],l-strlen(a[x]));
        }
        x++;
    }
    add(l,k);
    if(carry!=0)
    {
        cout<<carry;
    }
    while(o>=0)
    {
        cout<<(int)b[o];
        o--;
    }
}
void add(int l,int k)
{
    int lb=l-1;
    int r=k-1;
    int sum=0;
    int x=0;
    int neg=0;
    while(lb>=0)
    {
        r=k-1;
        sum=0;
        while(r>=0)
        {
            sum=sum+a[r][lb]-48;
            r--;
        }
        sum=sum+carry;
        lb--;
        if(sum>=10)
        {
            b[x]=sum%10;
            carry=sum/10;
        }
        else
        {
            b[x]=sum;
            carry=0;
        }
        sum=0;
        o=x;
        x++;
    }
}
void append(char a[], int temp)
{
    int l=0,m;
    int tempb=temp;
    m=strlen(a)-1;
    while(temp>0)
    {
        c[l]='0';
        l++;
        temp--;
    }
    int z=0;
    while(z<=m)
    {
        c[l]=a[z];
        z++;
        l++;
    }
    z=0;
    while(z<=m+tempb)
    {
        a[z]=c[z];
        z++;
    }
}

输入格式:第一行包含k,用于指定大数字的数目。接下来的k行中的每一行都包含一个大正整数。输出格式:对于每个测试用例,在新行中打印新的大整数

Sample Input:
3
1331331
1313
453535322
Sample Output:
454867966
Constraints:
1<=k<=10
1<=number of digits in big numbers<=10000

基于问题陈述:

  • 每个输入条目最多n个max=10000位
  • 由于每个条目都存储为C样式的零终止字符串,因此每个字符数组的长度必须为(nmax+1)=10001个字符,才能容纳C字符串终止符"\0"

当您将条目存储到字符数组中而不为零终止符留出空间时,假设每个条目都有10000个字符长:

  • k>=1的每个条目覆盖终止符或条目k-1,从而将条目合并在一起
  • 因此,您以一个巨大的字符串结束,其中l=strlen(a[0])=100000
  • 从那时起,所有进一步的处理都是用这些不正确的(合并的)输入和长度执行的,导致在稍后的执行中缓冲区溢出