算法提高 高精度加法

/*

问题描述
在C/C++语言中,整型所能表示的范围一般为-231到231(大约21亿),
    即使long long型,一般也只能表示到-263到263。要想计算更加规模的数,
    就要用软件来扩展了,比如用数组或字符串来模拟更多规模的数及共运算。
现在输入两个整数,请输出它们的和。
输入格式
两行,每行一个整数,每个整数不超过1000位
输出格式
一行,两个整数的和。
样例输入
15464315464465465
482321654151
样例输出
15464797786119616
数据规模和约定
每个整数不超过1000位
*/

#include<stdio.h>
void shuru( int [] , int *);
void q_nx( int [] , int );
void shuchu( int [] , int);
void q_he(int [] , int , int [] , int , int [] , int * );
void put_in(int [] , int [] , int [] , int  );
int main( void )
{
	int s1[1000]={0} ,s2[1000]={0} ,c[1001]={0};
	int cd1=0,cd2=0;
	shuru(s1 , &cd1 );
	shuru(s2 , &cd2 );
	int ws=0;
	q_he(s1 , cd1 , s2 , cd2 , c , &ws);
	shuchu( c , ws);
	return 0;
}
void put_in(int s1[] , int s2[] , int c[] , int cd )
{
	int i;
	for(i = 0 ; i < cd ; i ++)
	{
		c[i]=s1[i]+s2[i];
	}
}
void q_he(int s1[] , int cd1, int s2[] , int cd2, int c[] , int * ws)
{
	int n=cd1 > cd2 ? cd1 : cd2;
	put_in( s1 , s2 , c , n);
	int i;
	for(i = 0 ; i < n ; i ++)
	{
		c[i+1] += c[i]/10;
		c[i] %= 10;
		++ *ws;
	}
	if(c[n] > 0)
	{
		++ *ws;
	}
	
}
void shuchu( int sz[] , int n)
{
	int i;
	for( i = n-1 ; i >=0 ; i--)
	{
		printf("%d",sz[i]);
	}
}
void q_nx( int sz[] , int n)
{
	int tou=0,wei = n -1;
	while(tou < wei)
	{
		int tmp=sz[tou];
		sz[tou]=sz[wei];
		sz[wei]=tmp;
		tou++;
		wei--;
	}
}
void shuru( int sz[] , int * cd)
{
	char c;
	while((c = getchar()) !='\n' && c !=EOF)
	{
		sz[*cd] = c -'0';
		++ *cd ;
	}
	q_nx( sz , * cd );
}

猜你喜欢

转载自blog.csdn.net/qq_41353167/article/details/81742858