【PAT甲级 - C++题解】1005 Spell It Right

简介: 【PAT甲级 - C++题解】1005 Spell It Right

1005 Spell It Right

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
• 1

Sample Output:

one five


思路


用字符串 x 读入数字,然后计算每一位数的总和。注意,这里有个小技巧,计算字符串的每一位数可以通过 i - '0' 来求。

将要用到的单词用数组存起来,就不用反复 if else 了。

对总和 sum 进行字符串转化得到 res ,然后对 res 从前往后遍历,将数字转换成对应的单词并输出。这里同样要注意的是,在 PAT 中,对于输出的空格把控很严格,行尾不能有多余空格。所以我们可以先输出一个答案,然后再对后续答案进行统一化输出。


代码

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string x;
    cin >> x;
    //计算每一位数的总和
    int sum = 0;
    for (auto i : x)   sum += i - '0';
    //将字符串用数组存起来,方便使用
    string words[10] = { "zero","one","two","three"
        ,"four","five","six","seven","eight","nine" };
    //将结果进行字母转换
    string res = to_string(sum);
    cout << words[res[0] - '0'];
    for (int i = 1; i < res.size(); i++)
        cout << " " << words[res[i] - '0'];
    return 0;
}


目录
相关文章
|
6月前
|
Java 程序员 C语言
IT圈茶余饭后的“鄙视链” C,C++,Java,Python
IT圈茶余饭后的“鄙视链” C,C++,Java,Python
108 0
|
4月前
|
编译器 开发工具 C++
【Python】已解决error: Microsoft Visual C++ 14.0 or greater is required. Get it with “Microsoft C++ Build
【Python】已解决error: Microsoft Visual C++ 14.0 or greater is required. Get it with “Microsoft C++ Build
2162 0
|
传感器 IDE 开发工具
排错实战 —— 解决 c++ 工程编译错: error C2059 'string' illegal token on right
排错实战 —— 解决 c++ 工程编译错: error C2059 'string' illegal token on right
|
C++
【PAT甲级 - C++题解】1040 Longest Symmetric String
【PAT甲级 - C++题解】1040 Longest Symmetric String
66 0
|
算法 C++
【PAT甲级 - C++题解】1044 Shopping in Mars
【PAT甲级 - C++题解】1044 Shopping in Mars
82 0
|
C++
【PAT甲级 - C++题解】1117 Eddington Number
【PAT甲级 - C++题解】1117 Eddington Number
77 0
|
存储 C++ 容器
【PAT甲级 - C++题解】1057 Stack
【PAT甲级 - C++题解】1057 Stack
76 0
|
存储 C++
【PAT甲级 - C++题解】1055 The World‘s Richest
【PAT甲级 - C++题解】1055 The World‘s Richest
79 0
|
C++
【PAT甲级 - C++题解】1051 Pop Sequence
【PAT甲级 - C++题解】1051 Pop Sequence
80 0
|
人工智能 BI C++
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
136 0