微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

大数相加

             对于int,long,int64而言有时对我们所需要的数字远远超过了他们的范围,所以我们用一个int型数组来储存这个特别大的数,而两个大数相加更需要这种思想。大数相加在acm题目中也是常用到。

            我先定义了两个字符数组str1,str2。他们的长度为20000。还有一个ans字整数组他是存储最后的和。下面看代码吧,思路很简单。

           

/**
*大数加法
**/

#include<iostream>
#include<string.h>
using namespace std;

char num1[20000];
char num2[20000];
int ans[20001];

void Roll(char *s)
{
	int len = strlen(s);
	char temp;
	for(int i = 0; i < len/2;i++)
	{
		temp = s[i];
		s[i] = s[len-1-i];
		s[len-1-i] = temp;
	}
}

int main()
{
	while(true)
	{
		cin>>num1>>num2;
		int len1,len2;
		len1 = strlen(num1);
		len2 = strlen(num2);
		Roll(num1);
		Roll(num2);
		int len = 0;
		if(len1<len2)
		{
			int temp = 0;
			for(int i = 0; i <len2;i++)
			{
				if(i<len1)
				{
				ans[len++] = (num1[i]-'0'+num2[i]-'0'+ temp)%10 ;
				temp = (num1[i]-'0'+num2[i]-'0'+temp)/10;
				}
				else
				{
				ans[len++] = (num1[i]+num2[i]-'0'+ temp)%10 ;
				temp = (num1[i]+num2[i]-'0'+temp)/10;
				}
			}
			if(temp!=0)
			ans[len++] = temp;
		}
		else
		{
			int temp = 0;
			for(int i = 0; i < len1;i++)
			{
				if(i<len2)
				{
				ans[len++] = (num1[i]-'0'+num2[i]-'0'+temp)%10;
				temp = (num1[i]-'0'+num2[i]-'0'+temp)/10;
				}
				else
				{
				ans[len++] = (num1[i] +num2[i]-'0'+temp)%10;
				temp = (num1[i] + num2[i]-'0'+temp)/10;
				}
			}
			if(temp!=0)
				ans[len++] = temp;
		}

		for(int i = len-1; i >= 0 ;i--)
		{
			cout<<ans[i];
		}
		cout<<endl;
	}

	return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐