现在的位置: 首页 > 综合 > 正文

大整数相加

2013年05月03日 ⁄ 综合 ⁄ 共 1421字 ⁄ 字号 评论关闭
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>

// 思路如下
// 将两个字符串分别由低位到高位放置到int数组中
// 然后每位对齐相加,大于10,本位取余,高位进1

char* bigIntAdd( const char* numstr1, const char* numstr2 )
{
        assert( numstr1 != NULL && numstr2 != NULL );

        int len1 = strlen( numstr1 );
        int len2 = strlen( numstr2 );
        int resultLen = ( len1 > len2 ) ? ( len1 + 1 ) : ( len2 + 1 );//考虑进位,所以要多出一位

        int tmp1[resultLen]; // 放置第一个字符串由低位到高位的数字
        int tmp2[resultLen]; // 放置第二个字符串由低位到高位的数字

        int tmpResult[resultLen];
        memset( tmp1, 0, resultLen * sizeof(int) );
        memset( tmp2, 0, resultLen * sizeof(int) );
        memset( tmpResult, 0, resultLen * sizeof(int) );

	// 返回值结果
        char* addResult = new char[ resultLen + 1 ];// 末尾填'\0'
        memset(addResult, 0, resultLen*sizeof(char) );


        int i,j,k;
	// 取出由低位到高位的数字
        for ( i = 0; i < len1; i++ )
        {
                tmp1[i] = *( numstr1 + len1 - i - 1 ) - '0';
        }
        for ( i = len1; i < resultLen; i++ )
        {
                tmp1[i] = 0;
        }

        // 取出由低位到高位的数字
 	for ( j = 0; j < len2; j++ ) 
	{ 
		tmp2[j] = *( numstr2 + len2 - j - 1) - '0';
 	} 
	for ( j = len2; j < resultLen; j++ ) 
	{ 
		tmp2[j] = 0;
	 }
	// 求和
        int currSUM = 0;
        for ( k = 0; k < resultLen; k++ )
        {
                currSUM = tmp1[k] + tmp2[k];
                if ( currSUM > 9 )
                {
                        tmpResult[k] += currSUM - 10;
                        tmpResult[k+1] += 1;
                }
                else
                {
                        tmpResult[k] += currSUM;
                }
        }

        // 从后往前找到第一个不为零的数
        k = resultLen-1;
        while(!tmpResult[k])
        {
                k--;
        }

	// 返回值,字符串赋值
        for (int i = 0; i <= k; i++)
        {
                *(addResult + i) = tmpResult[k-i] + '0';
        }
        *(addResult+i) = '\0';


        return addResult;
}


int main()
{
        const char* str1 = "123456789";
        const char* str2 = "987654321";
        char* result = 0;
        result = bigIntAdd( str1, str2 );
        printf( "%s + %s = %s\n", str1, str2, result );

        // delete
        delete[] result;

        return 0;
}

// main output
kennie@cbib:~/cplusplus$ ./bigIntAdd.out
123456789 + 987654321 = 1111111110

抱歉!评论已关闭.