现在的位置: 首页 > 综合 > 正文

ZOJ 1205 Martian Addition (20进制加法)

2019年09月07日 ⁄ 综合 ⁄ 共 1687字 ⁄ 字号 评论关闭

Martian Addition

时间限制(普通/Java):2000MS/3000MS          运行内存限制:65536KByte
总提交:15            测试通过:7

描述

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.

输入

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.

输出

For each pair of numbers, write the sum of the 2 numbers in a single line.

样例输入

1234567890
abcdefghij
99999jjjjj
9999900001

样例输出

bdfi02467j
iiiij00000

 

解题思路:设和sum=0 ,先将sum = sum + a, 再将 sum = sum + b;

#include <iostream>
#include <cstring>
using namespace std;
char  a[101], b[101];
int sum[200];
int main() 
{
	int len1, len2, i, j, t;
	while (cin>>a>>b)
	{
		memset(sum, 0, sizeof(sum));
		len1 = strlen(a);
		len2 = strlen(b);
		for (i=len1-1,j=199; i>=0; i--, j--)
		{ 
			if (a[i]>='a')  //判断是的否大于10
				t = sum[j] + a[i] - 87;
			else
			t = sum[j] + a[i] - '0';
			sum[j] = t % 20;
			sum[j-1] = t / 20;
		}
		for (i=len2-1,j=199; i>=0; i--, j--)
		{ 
			if (b[i]>='a')
				t = sum[j] + b[i] - 87;
			else
			     t = sum[j] + b[i] - '0';
			sum[j] = t % 20;
			sum[j-1] += t / 20 ;
		}
		i = 0;
		while (sum[i]==0) i++;
		for (i; i<200; i++)
		{
			if (sum[i]<=9)cout<<sum[i];
			else cout<<char(sum[i]+87); //如果大于9,进行转换
		}
		cout<<endl;
	}
	return 0;
}

 

抱歉!评论已关闭.