PAT (Advanced) 1005. Spell It Right (20)

来源:互联网 发布:c语言用什么软件编写好 编辑:程序博客网 时间:2024/05/20 13:39

原题:1005. Spell It Right (20)



思路如下:

1.将英文字符串与数字对应做好表格

2.求出sum, 再分解sum, 最后根据表格输出

3.注意 0 的特殊处理


c++代码如下:

#include<cstdio>#include<algorithm>#include<cstring>using namespace std;char a[110];char table[10][10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};//打表int main(){    while(scanf("%s", a) != EOF)    {        int sum = 0;        int len = strlen(a);        for(int i = 0; i < len; i++)        {            sum += a[i] - '0';        }        int temp[10];        int cnt = 0;        if(sum == 0)// 0 的特殊处理        {            temp[0] = 0;            cnt = 1;        }        while(sum > 0) // sum 分解        {            temp[cnt++] = sum % 10;            sum /= 10;        }        for(int i = cnt - 1; i >= 0; i--)        {            if(i == cnt - 1)                printf("%s", table[temp[i]]);            else                printf(" %s", table[temp[i]]);        }        printf("\n");    }    return 0;}