问题描述
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。
你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。
问题分析
按照数字相加以及进位法则写出代码就行。
代码
char* addStrings(char* num1, char* num2) {
int length_num1 = 0;
int length_num2 = 0;
for(;num1[length_num1]!='\0'; length_num1++);
for(;num2[length_num2]!='\0'; length_num2++);
if(length_num1>length_num2){
int carry = 0;
int i,j;
for(i=length_num1-1,j = length_num2-1; i>=0&&j>=0; i--, j--){
int sum = carry + num1[i] - '0' + num2[j] - '0';
if(sum>=10){
carry = sum/10;
sum = sum%10;
}else{
carry = 0;
}
num1[i] = sum+'0';
}
for(;i>=0; i--){
int sum = carry + num1[i] - '0';
if(sum>=10){
carry = sum/10;
sum = sum%10;
}else{
carry = 0;
}
num1[i] = sum+'0';
}
if(carry!=0){
char * x = (char *)malloc(sizeof(char)*(length_num1+2));
for(int k = length_num1; k>=0; k--){
x[k+1] = num1[k];
}
x[0] = carry+'0';
return x;
}else{
return num1;
}
}else{
int carry = 0;
int i,j;
for(i=length_num1-1,j = length_num2-1; i>=0&&j>=0; i--, j--){
int sum = carry + num1[i] - '0' + num2[j] - '0';
if(sum>=10){
carry = sum/10;
sum = sum%10;
}else{
carry = 0;
}
num2[j] = sum + '0';
}
for(;j>=0; j--){
int sum = carry + num2[j] - '0';
if(sum>=10){
carry = sum/10;
sum = sum%10;
}else{
carry = 0;
}
num2[j] = sum+'0';
}
if(carry!=0){
char * x = (char *)malloc(sizeof(char)*(length_num2+2));
for(int k = length_num2; k>=0; k--){
x[k+1] = num2[k];
}
x[0] = carry + '0';
return x;
}else{
return num2;
}
}
}