【基礎算法】大數加法

##C++

#include <bits/stdc++.h>
#define rep( x, a, b )	for ( int x = a; x != b; ++x )
#define clr( x, val )	memset( x, val, sizeof(x) )
using namespace std;

string add( string str1, string str2 )
{
	char rs[10000];
	clr( rs, 0 );
	int maxLength = max( str1.size(), str2.size() );
	reverse( str1.begin(), str1.end() );
	reverse( str2.begin(), str2.end() );
	int	x	= 0;
	int	i	= 0;
	for (; i < maxLength; ++i )
	{
		int	a	= 0;
		int	b	= 0;
		if ( i <= str1.size() - 1 )
		{
			a = str1.at( i ) - '0';
		}
		if ( i <= str2.size() - 1 )
		{
			b = str2.at( i ) - '0';
		}
		int total = a + b + x;
		rs[i]	= (char) (total % 10 + '0');
		x	= total / 10;
	}
	if ( x > 0 )
		rs[i] = x;
	string end( rs );


	reverse( end.begin(), end.end() );
	printf( "%s", end.c_str() );
	return(end);
}


int main()
{
	add( "999999999999932132132132132132199", "213213123123213213213213123213213213123" );
	return(0);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章