火星A+B
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 8857 Accepted Submission(s): 2887
Problem Description
读入两个不超过25位的火星正整数A和B,计算A+B。需要注意的是:在火星上,整数不是单一进制的,第n位的进制就是第n个素数。例如:地球上的10进制数2,在火星上记为“1,0”,因为火星个位数是2进制的;地球上的10进制数38,在火星上记为“1,1,1,0”,因为火星个位数是2进制的,十位数是3进制的,百位数是5进制的,千位数是7进制的……
Input
测试输入包含若干测试用例,每个测试用例占一行,包含两个火星正整数A和B,火星整数的相邻两位数用逗号分隔,A和B之间有一个空格间隔。当A或B为0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即火星表示法的A+B的值。
Sample Input
1,0 2,1 4,2,0 1,2,0 1 10,6,4,2,1 0 0
Sample Output
1,0,1 1,1,1,0 1,0,0,0,0,0
#include"stdio.h"
#include<string>
#include<string.h>
#include<algorithm>
#include<stack>
using namespace std;
stack<int> turn(char buf[])
{
// printf("begin");
stack<int> s ;
int len = strlen(buf);
char temp[10];
int j;
for(int i = 0 ; i<len ; i++)
{
j=0;
while(i<len&&buf[i]!=',')
{
//printf("%c",buf[i]);
temp[j++]=buf[i++];
}
temp[j]='\0';
//printf("%s\n",temp);
int x = atoi(temp);
s.push(x);
}
return s;
}
int main()
{
char a[100];
char b[100];
int index[100];
bool flag [200];
stack<int> ai;
stack<int> bi;
stack<int> answer;
for(int i = 1 ; i<200 ; i++)//素数筛选法
{
flag[i]=true;
}
flag[1]=false;
for(int i = 2 ; i<200; i++)
{
for(int j = 2*i ; j<200; j+=i)
{
flag[j]=false;
}
}
int count = 1;
for(int i = 1 ; i<200 ; i++)
{
if(flag[i])
index[count++]=i;
}
//for(int i = 1 ; i<count ; i++)///
// printf("%d " , index[i]);
while(scanf("%s%s",a,b)!=EOF)
{
if(strlen(a)==1&&a[0]=='0'||strlen(b)==1&&b[0]=='0')
break;
else
{
ai = turn(a);
bi = turn(b);
/* while(!ai.empty())
{
printf("%d " , ai.top());
ai.pop();
}
while(!bi.empty())
{
printf("%d " , bi.top());
bi.pop();
}*/
int tempa;
int tempb;
int tempanswer;
int loc=1;
int c = 0 ; //进位
while(!ai.empty()&&!bi.empty())
{
tempa = ai.top();
ai.pop();
tempb = bi.top();
bi.pop();
tempanswer = (tempa+tempb+c)%index[loc];
c = (tempa+tempb+c)/index[loc++];
answer.push(tempanswer);
}
while(!ai.empty())
{
tempa = ai.top();
ai.pop();
tempanswer = (tempa+c)%index[loc];
c = (tempa+c)/index[loc++];
answer.push(tempanswer);
}
while(!bi.empty())
{
tempb = bi.top();
bi.pop();
tempanswer = (tempb+c)%index[loc];
c = (tempb+c)/index[loc++];
answer.push(tempanswer);
}
if(c==1)
answer.push(1);
printf("%d" , answer.top());
answer.pop();
while(!answer.empty())
{
printf(",%d" , answer.top());
answer.pop();
}
}
printf("\n");
}
return 0 ;
}