题解 | #大数加法#
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 计算两个数之和
* @param s string字符串 表示第一个整数
* @param t string字符串 表示第二个整数
* @return string字符串
*/
char* solve(char* s, char* t ) {
// write code here
int s1 = strlen(s) - 1;
int t1 = strlen(t) - 1;
printf("%d %d\n",s1,t1);
//判断非空
if (s1 == -1)
return t;
if (t1 == -1)
return s;
int c = 0;
char a[100000];int length = 0;
//对应位置相加
while (s1 > -1 && t1 > -1) {
a[length] = (s[s1] - '0' + t[t1] - '0' + c) % 10+'0';
c = (s[s1] - '0' + t[t1] - '0' + c) / 10;
length++;
s1--;
t1--;
}
if (s1 == -1) {
while (t1 > -1) {
a[length] = (t[t1] - '0' + c) % 10+'0';
c = (t[t1] - '0' + c) / 10;
length++;
t1--;
}
} else {
while (s1 > -1) {
a[length] = (s[s1] - '0' + c) % 10+'0';
c = (s[s1] - '0' + c) / 10;
length++;
s1--;
}
}
//最后一位有无进位
if(c>0){
a[length] = ('0' + c);
}else {
length--;
}
char *a1= malloc((length + 1) * sizeof(char));
int i;
for (i = length; i >= 0; i--) {
a1[length-i]=a[i];
}
a1[1+length]='\0';
return a1;
}
