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;
}