zoj 1205 Martian Addition

//这一题主要用到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;
	}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值