题目1010:A + B
思路:字符串分割采用strtok函数,把所有的数字单词都hash,得到唯一的能表示数字本身的值,这里采用120取模,得到单词对应的数字后,进行大数加法,最后得到结果
#include<stdio.h>
#include<string.h>
int m[120];
int hash(char *s)
{
int result=1;
int i=1;
for(;i<strlen(s);++i)
{
result+=s[i];
}
return result%120;
}
void init()
{
char *s[]={"zero","one","two","three","four",
"five","six","seven","eight",
"nine"};
for(int i=0;i<sizeof(s)/sizeof(char*);++i)
{
m[hash(s[i])]=i;
}
}
char s[100];
typedef struct node
{
int a[101];
int b[101];
int c[101];
int size;
}node;
void init2(node *n)
{
for(int i=0;i<101;++i)
{
n->a[i]=0;
n->b[i]=0;
n->c[i]=0;
}
}
int main(int argc, char *argv[])
{
init();
while(gets(s)!=NULL)
{
int a,b;
char *p=strtok(s," ");
int t=m[hash(p)];
while(p=strtok(NULL," "))
{
if(strcmp(p,"+")!=0)
{
t*=10;
t+=m[hash(p)];
}
else
break;
}
a=t;
p=strtok(NULL," ");
t=m[hash(p)];
while(p=strtok(NULL," "))
{
if(strcmp(p,"=")!=0)
{
t*=10;
t+=m[hash(p)];
}
else
break;
}
b=t;
if(a==0&&b==0)
return 0;
int i=0;
node a1;
init2(&a1);
while(a)
{
a1.a[i++]=a%10;
a/=10;
}
a1.size=i;
i=0;
while(b)
{
a1.b[i++]=b%10;
b/=10;
}
if(i>a1.size)
a1.size=i;
int carry=0;
for(int j=0;j<a1.size;++j){
t=a1.a[j]+a1.b[j]+carry;
a1.c[j]=t%10;
carry=t/10;
}
if(carry!=0){
a1.c[a1.size]=carry;
a1.size++;
}
for(int j=a1.size-1;j>=0;--j)
{
printf("%d",a1.c[j]);
}
printf("\n");
}
return 0;
}
/**************************************************************
Problem: 1010
User: kirchhoff
Language: C
Result: Accepted
Time:0 ms
Memory:920 kb
****************************************************************/