1. 程式人生 > >zoj 1205 Martian Addition(模擬)

zoj 1205 Martian Addition(模擬)

Martian Addition

Time Limit: 2 Seconds      Memory Limit: 65536 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

【分析】就是二十進位制運算....我也不知道為什麼 寫了一個下午...不知道最近什麼情況,寫什麼都要寫很久很久....

注意特例,01+0000000000001;0+0;就是前導很多0的時候要處理一下。然後就是,長度不一樣的話,前補0;

其他好像沒什麼要注意的。反正就是菜得不行,找錯誤找了那麼久。。好煩。。。

【程式碼】

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
char s1[105],s2[105];
char ss1[105],ss2[105];
int ans[205];
int add(char a,char b)
{
	int z;
	if(isdigit(a))
	{
		if(isdigit(b)) z=a-'0'+(b-'0');
		else z=(a-'0')+(b-'a'+10);
	}
	else
	{
		if(isdigit(b))z=a-'a'+10+(b-'0');
		else z=a-'a'+10+(b-'a'+10);
	}
	return z;
}
int main()
{
	while(~scanf("%s%s",s1,s2))
	{
		memset(ans,0,sizeof(ans));
		memset(ss1,0,sizeof(ss1));
		memset(ss2,0,sizeof(ss2));
		int len1=strlen(s1),len2=strlen(s2);
		for(int i=len1-1;i>=0;i--)
			ss1[len1-1-i]=s1[i];
		for(int i=len2-1;i>=0;i--)
			ss2[len2-1-i]=s2[i];
		int len=max(len1,len2);
		for(int i=len1;i<105;i++)ss1[i]='0';//注意這裡不要寫錯,是ss1/ss2不是s1/s2;並且是從len而不是len-1開始,不然會抹掉一個數據的 
		for(int i=len2;i<105;i++)ss2[i]='0';
		for(int i=0;i<len;i++)
		{
			int z=add(ss1[i],ss2[i]);
			ans[i]+=z;
			if(ans[i]>=20)
			{
				ans[i+1]+=ans[i]/20;
				ans[i]=ans[i]%20;
			}
		}
		int kk=0;
		while(ans[len]==0)len--;
		for(int i=len;i>=0;i--)
		{
			kk=1;
			if(ans[i]<=9)printf("%d",ans[i]);
			else
			printf("%c",ans[i]-10+'a');
		}
		if(!kk)puts("0");//相加是0的情況 
		else puts("");//換行 
	}
	return 0;
}