//这一题主要用到map映射器!要注意进位的处理就可以了!到相加到最后,还需要注意是否有进位!
#include "iostream"
#include "map"
#include "string"
#include "algorithm"
using namespace std;
int main()
{
map<char, int> m;
map<int, char> mm;
char ch1 = '0' ,ch2 = 'a';
string str1, str2;
//给map容器的赋值
for (int i = 0; i < 10; i++)
m.insert(pair<char, int>(ch1+i, i));
for (int i = 10, j = 0; i < 20; i++, j++)
m.insert(pair<char, int>(ch2+j, i));
for (int i = 0; i < 10; i++)
mm.insert(pair<int, char>(i, ch1+i));
for (int i = 10, j = 0; i < 20; i++, j++)
mm.insert(pair<int, char>(i, ch2+j));
while (cin >> str1 >> str2)
{
int length1, length2, temp, carry = 0;
string ans = "";
length1 = str1.size();
length2 = str2.size();
if (length1 >= length2)//分两种情况进行处理!
{
for (int i = length1-1, j = length2-1; j >=0 ; i--, j--)
{
temp = m[str1[i]] + m[str2[j]] + carry;
if (temp >= 20)//判断是否需要进位
{
carry = temp / 20;
temp %= 20;
}
else
carry = 0;
ans += mm[temp];
}
for (int i = length1-length2-1; i >= 0 ; i--)//当两个字符串的长度不相等的时候,还需要处理长字符串剩下的部分!
{
if (carry == 0)
ans += str1[i];
else
{
int temp1;
temp1 = m[str1[i]] + carry;
if (temp1 >= 20)
{
carry = temp1 / 20;
temp1 %= 20;
}
else
carry = 0;
ans += mm[temp1];
}
}
if (carry != 0)//如果最后还有进位的,还需要添加到最后的结果中
ans += carry + 48;
}
else//这种情况和上面的做法一样,只是字符串的长度所影响!
{
for (int i = length1-1, j = length2-1; i >=0 ; i--, j--)
{
temp = m[str1[i]] + m[str2[j]] + carry;
if (temp >= 20)
{
carry = temp / 20;
temp %= 20;
}
else
carry = 0;
ans += mm[temp];
}
for (int i = length2-length1-1; i >= 0 ; i--)
{
if (carry == 0)
ans += str2[i];
else
{
int temp1;
temp1 = m[str2[i]] + carry;
if (temp1 >= 20)
{
carry = temp1 / 20;
temp1 %= 20;
}
else
carry = 0;
ans += mm[temp1];
}
}
if (carry != 0)
ans += carry + 48;
}
reverse(ans.begin(), ans.end());//反转字符串输出!
cout << ans << endl;
}
zoj 1205 Martian Addition
最新推荐文章于 2019-07-20 08:32:46 发布