这题我用字符数组正向保存数字,即数组第一个字符表示数字的最高位。
为了处理加法后结果最高位增加一位的情况,想要把数组中的元素整体后移一位,将首位空出来。
strcpy(&(a[1]), a);
strcpy(&(b[1]), b);
但是最后一个测试点过不了,下载了数据是这样的
输入
350204156568812004512541458715942878921069349854678
5120132301230048014584016540526804565814706519846494321001345794503242112976563432120
输出
5120132301230048014584016540526804916018863088658498833542804510446121034045913286798
这组数据用上面的代码来后移一位的时候数据会改变
我数组开的是足够大了
char temp[505] = { 0 };
strcpy(temp, a);
strcpy(&(a[1]), temp);
char temp1[505] = { 0 };
strcpy(temp, b);
strcpy(&(b[1]), temp);
难不成strcpy();有什么问题吗?
#include <stdio.h>
#include <string.h>
int main() {//最高位在字符数组首位
char a[505] = { 0 };
char b[505] = { 0 };
scanf("%s\n%s", a, b);
int enda = strlen(a);
int endb = strlen(b);
if (enda < endb) {
char temp[505] = { 0 };
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
int tempi = enda;
enda = endb;
endb = tempi;
}
//集体后移
char temp[505] = { 0 };
strcpy(temp, a);
strcpy(&(a[1]), temp);
char temp1[505] = { 0 };
strcpy(temp, b);
strcpy(&(b[1]), temp);
/*strcpy(&(a[1]), a);
strcpy(&(b[1]), b);*/
a[0] = '0';
b[0] = '0';
int sum = 0;// a[enda] - '0' + b[endb] - '0';
while (endb >= 0) {
sum += a[enda] - '0' + b[endb] - '0';
a[enda] = sum % 10 + '0';
sum /= 10;
enda--;
endb--;
}
while (sum != 0) {//a一直进一的可能性
sum += a[enda] - '0';
a[enda] = sum % 10 + '0';
sum /= 10;
enda--;
}
if (a[0] == '0') {
printf("%s", &a[1]);
}
else {
printf("%s", &a[0]);
}
return 0;
}