1205_Martian Addition

  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

******************************************************************

#include<iostream>
#include<vector>
#include<string>
using namespace std;
void equ(string,string,string,vector<int>);
int main()
{
string s0("0123456789abcdefghij");
string s1,s2;
vector<int> v1;
int num;
while(cin>>s1>>s2)
{
if(s1.size()==s2.size())//两个数长度相等
equ(s0,s1,s2,v1);
else //两数长度不相等(题中并没有举出两数不相等的例子,但是只有这样才能ac...)
{
if(s1.size()>s2.size())
{
                num=s1.size()-s2.size();
   for(int i=0;i!=num;i++)
              s2.insert( 0,"0");//在短的前面补"0",和长的size相同(技巧!!!)
}
else
{
num=s2.size()-s1.size();
   for(int i=0;i!=num;i++)
              s1.insert( 0,"0");
}
equ(s0,s1,s2,v1);
}
}
return 0;
}
void equ(string s0,string s1,string s2,vector<int> v1)
{
   int a,b,c,d;
   c=0; 
for(int i=s1.size()-1;i>=0;i--)
{
if(s1[i]<=57)//将string转换为实际值
a=s1[i]-48;
else
a=s1[i]-87;
if(s2[i]<=57)
b=s2[i]-48;
else
b=s2[i]-87;
d=a+b+c;
if(d>=20)//进位,因为是两个数相加,所以进位最多为1;
{
d-=20;
c=1;
}
else
c=0;
v1.push_back(d);
}
if(c==1)
  v1.push_back(c);//最高为进位
for(vector<int>::iterator iter=v1.end()-1;iter>v1.begin();--iter)//倒序输出时,若是iter>=v1.begin();输出最后一个后,会地址越界,只能这样
cout<<s0[*iter];
cout<<s0[v1[0]]<<endl;
v1.clear();
}

你可能感兴趣的:(1205_Martian Addition)