[PAT甲级]1005 Spell It Right (20 分)

题目

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 (≤10
​100
​​ ).

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

分析

考察字符串与数字的转化
由于输入的范围N (≤10的100次方).远远大于int,所以要用字符串存储。
同时要考虑到0的情况。

代码

#include<iostream>
#include<map>
#include<string>
#include<stack>
using namespace std;
string str[11]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int main(){
    string x;
    cin>>x;
    
    if(x=="0"){
        cout<<"zero";
        return 0;
    }
    
    stack<int>s;
    int num=0;
    for(int i=0;i<x.length();i++){
        num+=(x[i]-'0');
    }

    while (num>0) {
        s.push(num%10);
        num/=10;
    }
    cout<<str[s.top()];
    s.pop();
    while (!s.empty()) {
        cout<<" "<<str[s.top()];
        s.pop();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容