FJNU.1865
Description
In the 22nd Century, scientists have discovered intelligent residents live on the Mars. Martians are very fond of mathematics. Every year, they would hold an Arithmetic Contest on Mars (ACM). The task of the contest is to calculate the sum of two 100-digit numbers, and the winner is the one who uses least time. This year they also invite people on Earth to join the contest.
As the only delegate of Earth, you're sent to Mars to demonstrate the power of mankind. Fortunately you have taken your laptop computer with you which can help you do the job quickly. Now the remaining problem is only to write a short program to calculate the sum of 2 given numbers. However, before you begin to program, you remember that the Martians use a 20-based number system as they usually have 20 fingers.
Input
You're given several pairs of Martian numbers, each number on a line.
Martian number consists of digits from 0 to 9, and lower case letters from a to j (lower case letters starting from a to present 10, 11, ..., 19).
The length of the given number is never greater than 100.
Output
For each pair of numbers, write the sum of the 2 numbers in a single line.
Sample Input
1234567890
abcdefghij
99999jjjjj
9999900001
Sample Output
bdfi02467j
iiiij00000
Source
Zhejiang University Local Contest 2002, Prelimina
My Program
#include<iostream>
#define N 100
using namespace std;
inline int ToInt(char n)
...{
if(n>='0'&&n<='9')
return n-'0';
else
return n-'a'+10;
}
inline char ToChar(int x)
...{
if(x<10)
return '0'+x;
else
return 'a'+x-10;
}
int main()
...{
char a[N+1],b[N+1];
int x[N+1],i,m,n,k;
while(scanf("%s %s",a+1,b+1)!=EOF)
...{
a[0]=b[0]='0';
m=strlen(a);n=strlen(b);
k=m>n?m:n;
for(i=0;i<=k;i++)
x[i]=0;
if(m>n)
...{
for(i=n-1;i>0;i--)
...{
x[i+m-n]+=ToInt(a[i+m-n])+ToInt(b[i]);
if(x[i+m-n]>=20)
...{
x[i+m-n-1]++;
x[i+m-n]-=20;
}
a[i+m-n]=ToChar(x[i+m-n]);
}
for(i=m-n;i>0;i--)
...{
x[i]+=ToInt(a[i]);
if(x[i]>=20)
...{
x[i-1]++;
x[i]-=20;
}
a[i]=ToChar(x[i]);
}
a[0]=ToChar(x[0]);
a[m]='/0';
if(a[0]!='0')
cout<<a<<endl;
else
cout<<a+1<<endl;
}
else
...{
for(i=m-1;i>0;i--)
...{
x[i+n-m]+=ToInt(a[i])+ToInt(b[i+n-m]);
if(x[i+n-m]>=20)
...{
x[i+n-m-1]++;
x[i+n-m]-=20;
}
b[i+n-m]=ToChar(x[i+n-m]);
}
for(i=m-n;i>0;i--)
...{
x[i]+=ToInt(b[i]);
if(x[i]>=20)
...{
x[i-1]++;
x[i]-=20;
}
b[i]=ToChar(x[i]);
}
b[0]=ToChar(x[0]);
b[n]='/0';
if(b[0]!='0')
cout<<b<<endl;
else
cout<<b+1<<endl;
}
}
return 0;
}YOYO's Note:
高精度(100位字符串比较)+20进制。
我从最后一位起逐步向前进位……
因为有可能前面新进一位,数组从1开始,0原来放是否新进位……
本文介绍了一个模拟火星数学竞赛中算术部分的程序实现。该程序使用C++编写,能够处理两个长度不超过100位的二十进制数相加的问题。通过对输入字符进行转换并逐位计算,最终输出两数之和。

248

被折叠的 条评论
为什么被折叠?



