PAT-A 1005. Spell It Right (20)

传送门

https://www.patest.cn/contests/pat-a-practise/1005

题目

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

分析

将读入的内容作为字符串,根据其顺序将各位数字相加,然后将和的每位数字按序压栈,再根据每个数字输出对应的英文单词即可。

源代码

//C/C++实现
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(){
    string s;
    cin >> s;
    int sum = 0;
    for(int i = 0; i < s.size(); ++i){
        sum += s[i] - '0';
    }
    vector<int> v;
    if(sum != 0){
        while(sum != 0){
            v.push_back(sum % 10);
            sum /= 10;
        }
    }
    else{
        v.push_back(0);
    }
    for(int i = v.size() - 1; i >= 0; --i){
        if(i != v.size() - 1){
            printf(" ");
        }
        switch(v[i]){
            case 0: printf("zero");break;
            case 1: printf("one");break;
            case 2: printf("two");break;
            case 3: printf("three");break;
            case 4: printf("four");break;
            case 5: printf("five");break;
            case 6: printf("six");break;
            case 7: printf("seven");break;
            case 8: printf("eight");break;
            case 9: printf("nine");break;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 小学同学会,正值毕业40周年大庆,因此场面布置得热烈隆重。主持人激动地宣布—— 我们尊敬的班主任陈素华老师到了! ...
    周长风阅读 477评论 0 0
  • 文/刘万军 睏倦卧柴门, 不歇护主心。 闲花轻落地, 误作不良人。
    刘万军L阅读 170评论 0 1
  • 如果可以满足你的条件,我愿意用我的一生来判断 疏影横斜水清浅 暗香浮动月黄昏 我希望世界和平。 这样的情况,如果可...
    施展君阅读 189评论 0 1
  • 《嫌疑人X的献身》是日本推理作家东野圭吾的神作,是推理界里一颗闪耀的明珠。曾经被翻拍过日本版和韩国版,都有过很不错...
    李惟文阅读 2,612评论 0 0
  • 朱東革阅读 157评论 0 0