60-题目1198:a+b

65 篇文章 0 订阅
53 篇文章 0 订阅

http://ac.jobdu.com/problem.php?pid=1198

题目描述:

实现一个加法器,使其能够输出a+b的值。

输入:

输入包括两个数a和b,其中a和b的位数不超过1000位。

第一种方法,直接用char数组,但是要时不时的注意  '0':

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

int main()
{

	int i, j, temp;
	char a[1010], b[1010], res[1010];
	ifstream cin("data.txt");
	while (cin >> a >> b)
	{
		int len1, len2, min, c = 0;
		len1 = strlen(a);
		len2 = strlen(b);
		min = len1 >= len2 ? len2 : len1;  //取长度的较小值
		for (i = 0; i < min; i++)
		{
			temp = a[len1 - 1 - i] - '0' + b[len2 - 1 - i] - '0' + c;
			if (temp >= 10)//有进位
				c = 1;
			else
				c = 0;
			temp = temp % 10;   //余位存储,进位加1
			res[i] = temp + '0';//这里有问题,是直接赋值还是要加上‘0’
		}
		if (len1 > len2)
		{
			for (j = len1 - min; j > 0; j--)  //还剩len1-min个数字
			{
				temp = a[j - 1] - '0' + c;
				if (temp >= 10)//有进位
					c = 1;
				else
					c = 0;
				temp = temp % 10;   //余位存储,进位加1
				res[i++] = temp + '0';//这里有问题,是直接赋值还是要加上‘0’
			}
			if (c == 1)
				res[i++] = 1 + '0';		
		}
		else if(len1 < len2)
		{
			for (j = len2 - min; j > 0; j--)  //还剩len1-min个数字
			{
				temp = b[j - 1] - '0' + c;
				if (temp >= 10)//有进位
					c = 1;
				else
					c = 0;
				temp = temp % 10;   //余位存储,进位加1
				res[i++] = temp + '0';//这里有问题,是直接赋值还是要加上‘0’
			}
			if (c == 1)
				res[i++] = 1+ '0';
		}
		for (j = i; j > 0; j--)   //逆序输出
			cout << res[j - 1] - '0';
		cout << endl;
	}//end of while
	system("pause");
	return 0;
}
第二种方法,不用char数组加,直接用int数组,更简单:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
	int i, j, temp, len1, len2;
	string str1, str2;
	ifstream cin("data.txt");
	while (cin >> str1 >> str2)
	{
		int a[1010] = { 0 }, b[1010] = { 0 };
		len1 = str1.length();
		len2 = str2.length();
		for (i = len1; i > 0; i--)  //个位在0位
			a[len1-i] = str1[i - 1] - '0';
		for (i = len2; i > 0; i--)
			b[len2 - i] = str2[i - 1] - '0';

		int max = len1 >= len2 ? len1 : len2;
		for (i = 0; i < max; i++)    //往后进位,逆序输出
		{
			temp = a[i] + b[i];
			b[i] = temp % 10;
			if (temp >= 10)
				b[i + 1]++;    //当for运行完了,出来的i是要输出的最高位加1
		}
		if (len1 > len2)//把a剩余的元素加到b上去
		{
			while (i < len1)
			{
				b[i] += a[i];
				if (b[i] >= 10)
					b[i + 1]++;
				b[i] = temp % 10;
				i++;       //当while运行完了,出来的i就是要输出的最高位
			}		
		}
		if (b[i] == 1) cout << b[i];    //这里因为有len1>len2这一步的存在的可能性,所以不确定i的最终位置
		for (j = i; j > 0; j--)
			cout << b[j-1];
		cout << endl;
	}//end of while
	system("pause");
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值