实现两个超大无符号整数的加法(现有基本数据类型无法存储)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int AddBigNum ( const char *pA, const char *pB, char *pSum, int nSumMaxLen);
int main ( int argc, char **argv )
{
int len;
char str[1000];
char str1[1000];
char str2[1000];
scanf("%s",str);
scanf("%s",str1);
len = AddBigNum ( str, str1, str2, 0);
if( str2[ 0 ] == '0')
{
for ( int i = 1; i < len ; i++)
{
printf("%c", str2[ i ]);
}
}
else
{
for ( int i = 0; i < len; i++)
{
printf("%c", str2[i]);
}
}
putchar ( 10 );
}
int AddBigNum ( const char *pA, const char *pB, char *pSum, int nSumMaxLen)
{
int len_a = strlen ( pA );//计算字符串A长度
int len_b = strlen ( pB );//计算字符串B长度
const char *max;
const char *min;
int len_max = (len_a -len_b >= 0) ? len_a : len_b;//把字符串长的给len_max
int len_min = (len_a - len_b < 0) ? len_a : len_b;//把字符串短的给len_min
max = (len_a - len_b >= 0) ? pA : pB;//把字符串长的给max
min = (len_a - len_b < 0) ? pA : pB;//把字符串短的给min
nSumMaxLen = len_max + 1;//和的长度加1 进位
pSum[ 0 ] = '0';//和的最高位给0
for( int i = 0; i < len_max - len_min; ++i)
{
pSum[ i + 1 ] = max[ i ];//字符串长的前len_max-len_min 字符给到pSum
}
for( int i = len_max - len_min; i < len_max; ++i)
{
if( pA[ i ] + pB[ i - len_max + len_min ] - '0' > '9' )//判断有无进位
{
pSum[ i + 1 ] = max[ i ] + min[ i - len_a + len_b] - '0' - 10;//本位减10
int j = i ;
while ( (pSum[ j ] = pSum[ j ] + 1) > '9' )//进位加1 判断是否还需要进位
{
pSum[ j ] = pSum[ j ] - 10;
j-- ;
}
}
else
{
pSum[ i + 1 ] = max[ i ] + min[ i - len_a + len_b ] - '0';//不需要进位
}
}
return nSumMaxLen;
}