PAT A1005: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 (\leqslant 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

题目要点

本题 20 分,比较简单。尽量不要使用 Python,个别测试点可能会超时。

AC 源代码

#include <iostream>
#include <string>
#include <map>
using namespace std;

int main() {
    string digit;
    int sum = 0;
    map<char, string> letter = {
        {'0', "zero"},
        {'1', "one"},
        {'2', "two"},
        {'3', "three"},
        {'4', "four"},
        {'5', "five"},
        {'6', "six"},
        {'7', "seven"},
        {'8', "eight"},
        {'9', "nine"}
    };

    cin >> digit;
    for (int i = 0; i < digit.size(); i++)
        sum += (int)digit[i] - 48;
    string str = to_string(sum);
    for (int i = 0; i < str.size(); i++) {
        cout << letter[str[i]];
        if (i < str.size()-1)
            cout << ' ';
    }
    return 0;
}