1005. Spell It Right (20)

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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章