码迷,mamicode.com
首页 > 其他好文 > 详细

九度OJ 1010 A+B

时间:2015-01-02 09:42:26      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:九度oj   1010   

题目1010:A + B

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:5913

解决:3075

题目描述:
读入两个小于100的正整数A和B,计算A+B.
需要注意的是:A和B的每一位数字由对应的英文单词给出.
输入:
测试输入包含若干测试用例,每个测试用例占一行,格式为"A + B =",相邻两字符串有一个空格间隔.当A和B同时为0时输入结束,相应的结果不要输出.
输出:
对每个测试用例输出1行,即A+B的值.
样例输入:
one + two =
three four + five six =
zero seven + eight nine =
zero + zero =
样例输出:
3
90
96
思路:字符串分割采用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
****************************************************************/



九度OJ 1010 A+B

标签:九度oj   1010   

原文地址:http://blog.csdn.net/wdkirchhoff/article/details/42317345

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!