1005. Spell It Right (20)

来源:互联网 发布:mysql 查找第一条记录 编辑:程序博客网 时间:2024/05/24 03:45

Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.

Input Specification:

Each input file contains one test case. Each case occupies one line which contains an N (<= 10100).

Output Specification:

For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.

Sample Input:
12345
Sample Output:

one five



最初题目看错了,以为直接写出对应数字的英文,

其实题意事输入一串数字,对每个数字相加,得到的和后用英文输出,中间有空格,最后一个无空格。


#include<iostream>
using namespace std;
int main (){
string n;
int temp[11];
int t=0,sum=0;
string eng[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
cin>>n;
//求和 
for(int i=0;i<n.length();i++)
sum+=n[i]-'0';
//分离数字 
while(1){
temp[t]=sum%10;
sum/=10;
if(sum==0)
break;
t++;
}
//结果输出 
for(int i=t;t>=0;t--){
cout<<eng[temp[t]];
if(t!=0)
cout<<" ";
}


cout<<endl;
return 0;


下面是我在网上看到的一个代码,解释比较详细,用到的知识点更多些

#include<iostream>
#include<stack>
#include<string.h>


char *g_WordTable[10]= {"zero", "one", "two", "three", "four", "five","six", "seven", "eight", "nine"};


int main()
{
    //存放用户输入的数据 
    char input[1000];
    //当用户输入的数据没有停止的时候 
    while(scanf("%s", &input) != EOF)
    {
        int sum = 0;
        //得到用户输入数据的长度,用到了string.h
        int len = strlen(input);
        //把每个字符转化为ASCII码,数字字符的ASCII码和数字本身是相等的,求和 
        for(int i = 0; i < len; ++i)
            sum += (input[i]-'0');
        //定义一个栈 
        std::stack<int> s;
        //拆位,个位先放入栈,然后是十百千位 
        do
        {
            int temp = sum%10;
            s.push(temp);
            sum /= 10;
        }while(sum != 0);
        //输出,empty判断堆栈是否为空 
        while(!s.empty())
        {   //得到堆栈栈顶数据
            int t = s.top();
            //size返回当前堆栈长度(即内部数据个数) 
            //如果栈的大小事大于1的 
            if((int)s.size() > 1)
                printf("%s ", g_WordTable[t]);
            else 
                printf("%s\n", g_WordTable[t]);
            //pop弹出栈顶的元素 
            s.pop();
        }
    }
    return 0;
}