求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
- 从那时起,所有进一步的处理都是用这些不正确的(合并的)输入和长度执行的,导致在稍后的执行中缓冲区溢出
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组