Martian Addition
Time Limit: 1 Second Memory Limit: 32768 KB
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
一道水题,整个思想很简单,就是要用数组来存储每一个数字和字母,然后根据ASCI码表的序号比较得出是每一位的字符
虽说是一道水题,但需要考虑周全,之前因为漏了一种情况,少了一个判断条件,结果老是WA
哎,要考虑周全才行啊!我用的方法,可以运用于高精度的加法运算。高精度加法的思想应该跟这个差不多吧
我的代码:(因为我不知道用scanf怎么读取string类型,所以就用C++的cin,cout了)
#include<string> #include<iostream> using namespace std; int main() { string a,b; string c="abcdefghij"; while(cin>>a>>b) { if(a.length()<b.length()){ string temp=a; a=b; b=temp; } for(int n1=a.length()-1,n2=b.length()-1;n1>=0;n1--,n2--) { if(a[n1]-39>'9')a[n1]=a[n1]-39; if(b[n2]-39>'9')b[n2]=b[n2]-39; a[n1]=char(a[n1]+(n2>=0?b[n2]-'0':0)); if(a[n1]-'0'>=20) { a[n1]=char(int((a[n1]-'0')%20)+'0'); if(n1) a[n1-1]++; else { if(a[n1]!='0') a[n1]=c[int(a[n1]-'9')-1]; a='1'+a; } } if(a[n1]>'9') { a[n1]=c[int(a[n1]-'9')-1]; } } cout<<a<<endl; } return 0 ; }