思路
- 将大整数的字符串数组从后向前逐位相加
- 用dif表示两个数组长度的差,takeOver 表示每一位计算后的进位,长度为最大长度+1的result字符数组存储相加后的结果
- 先计算后dif位的和;
- 如果dif>0,再将剩下的高位与地位的进位相加,拷贝到result数组的前dif位,得到结果;
- 如果dif==0, 直接将进位放到result[0]的位置,得到结果;
C++实现代码如下:
#include <bits\stdc++.h>
using namespace std;
char * numberAdd(char * number1, char * number2){
int len1 = strlen(number1);
int len2 = strlen(number2);
char * min_len_number;
char * max_len_number;
int min_len,max_len;
int dif;
if(len1>=len2){
min_len = len2;
min_len_number = number2;
max_len = len1;
max_len_number = number1;
}
else{
min_len = len1;
min_len_number = number1;
max_len = len2;
max_len_number = number2;
}
dif = max_len-min_len;
char * result = new char[max_len+2];
memset(result,'0',max_len+1);
result[max_len+1] = '\0';
int takeOver = 0;
for(int i=max_len-1;i>=dif;i--){
int sum = (max_len_number[i]-'0')+(min_len_number[i-dif]-'0')+takeOver;
takeOver = 0;
if(sum>=10){
takeOver = 1;
sum -= 10;
result[i+1] = sum + '0';
}
else{
result[i+1] = sum+'0';
}
cout<<i<<' '<<result<<endl;
}
// cout<<result<<endl;
if(dif>0){
for(int i=dif-1;i>=0;i--){
int sum = max_len_number[i]-'0'+takeOver;
takeOver = 0;
if(sum>=10){
if(i==0){
result[i] = '1';
}
else{
takeOver = 1;
sum -= 10;
result[i+1] = sum + '0';
}
}
else{
result[i+1] = sum + '0';
}
}
}
else{
result[0] = takeOver+'0';
}
// cout<<result<<endl;
return result;
}
void printResult(char * result){
int len = strlen(result);
int i=0;
while(result[i]=='0'){
i++;
}
while(i<len){
cout<<result[i++];
}
}
int main(){
char * number1 = "99999999999999999999999999999999999999999999999999999999999999999";
char * number2 = "1";
char * result;
result = numberAdd(number1,number2);
printResult(result);
cout<<endl;
return 0;
}