题目链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=1503
总结:多个长度最多为n为的数相加,结果可能为n+2位,调整完毕后要检测最高为是否大于等于10和是否大于0两种情况;
计算结果的长度时,可以通过count来维护,也可以通过最后反向查找第一个非0的数所在的位置,来确定长度。
版本一:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
char op[101];
int i,j,res[102];
memset(res,0,sizeof(res));
while(cin >> op)
{
if(strlen(op) == 1 && op[0] == '0')
break;
reverse(op,op + strlen(op));
i = 0;
while(op[i] != '/0')
{
res[i] += op[i] - '0';
if(res[i] > 9)
{
res[i] -= 10;
++res[i+1];
}
++i;
}
++j;
}
j = 101;
while(j >= 0 && res[j] == 0)
--j;
if(j >= 0)
{
for(i = 0;i < j;++i)
{
if(res[i] > 9)
{
res[i+1] += res[i] / 10;
res[i] = res[i] % 10;
}
}
if(res[j] != 0)
++j;
i = j - 1;
while(i >= 0)
{
cout << res[i];
--i;
}
cout << endl;
}
else
cout << 0 << endl;
return 0;
}
版本二:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
freopen("in.txt","r",stdin);
char op[101],res[103];
int tmp[102],i,count;
memset(tmp,0,sizeof(tmp));
count = 0;
while(cin >> op)
{
if(strlen(op) == 1 && op[0] == '0')
break;
reverse(op,op + strlen(op));
i = 0;
while(op[i] != '/0')
{
tmp[i] += op[i] - '0';
++i;
}
if(i > count)
count = i;
}
i = 0;
while(i < count)
{
if(tmp[i] > 9)
{
tmp[i+1] += tmp[i] / 10;
tmp[i] %= 10;
}
++i;
}
if(tmp[i] > 0)
{
if(tmp[i] >= 10)
{
tmp[i+1] = tmp[i] / 10;
tmp[i] %= 10;
count += 2;
}
else
++count;
}
for(i = 0;i < count;++i)
res[i] = tmp[i] + '0';
res[i] = '/0';
reverse(res,res + strlen(res));
cout << res << endl;
return 0;
}
版本三:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
char op[101];
int i,count,res[102];
memset(res,0,sizeof(res));
while(cin >> op)
{
if(strlen(op) == 1 && op[0] == '0')
break;
reverse(op,op + strlen(op));
i = 0;
while(op[i] != '/0')
{
res[i] += op[i] - '0';
++i;
}
}
count = 101;
while(count >= 0 && res[count] == 0)
--count;
i = 0;
while(i <= count)
{
res[i+1] += res[i] / 10;
res[i] %= 10;
++i;
}
if(res[i] > 0)
{
if(res[i] > 9)
{
res[i+1] = res[i] / 10;
res[i] %= 10;
count += 2;
}
else
++count;
}
while(count >= 0)
{
cout << res[count];
--count;
}
cout << endl;
return 0;
}
版本四:几天后又做了一边,这次的代码思路更清晰,考虑到100个100位的9才102位,所以结果最多位103位
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define MAX 103
int main()
{
freopen("in.txt","r",stdin);
char op[MAX],res[MAX];
int i,p_len,r_len,len;
for(i = 0;i < MAX;++i)
res[i] = 0;
r_len = 0;
while(cin >> op)
{
p_len = strlen(op);
if(p_len == 1 && op[0] == '0')
break;
reverse(op,op + p_len);
len = p_len > r_len ? p_len : r_len;
for(i = 0;i < len;++i)
{
if(i < p_len)
{
res[i] += op[i] - '0';
if(res[i] > 9)
{
++res[i+1];
res[i] -= 10;
}
}
else
{
if(res[i] > 9)
{
++res[i+1];
res[i] -= 10;
}
}
}
if(res[i] != 0)
++len;
r_len = len;
}
while(r_len > 1 && res[r_len-1] == 0)
--r_len;
for(i = 0;i < r_len;++i)
res[i] += '0';
reverse(res,res + r_len);
cout << res << endl;
return 0;
}