PAT 1005 Spell It Right (20分)

Scroll Down


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:
Sample Output:
one five



也就是 123 要输出成 one two three ,并且最后面不能有多余空格。

注意: N 最大可以取到 10100,所以千万不要用 int,long long 。。。用 string !!!!




#include <iostream>
using namespace std;

int main() {
    // int 无法存储
    string strNum;
    cin >> strNum;
    int len = strNum.length();
    int sum = 0;
    // 每一位加起来
    for (int i = 0; i < len; ++i) {
        sum += (strNum[i] - '0');
    // 结果转为字符串,每一位用英文表示
    string strSum = to_string(sum);
    // 映射表
    string map[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    // 输出第一个位置
    cout << map[strSum[0] - '0'];
    // 输出 空格 其他位置,这样可以满足输出格式要求,最末尾不能有多余空格
    len = strSum.length();
    for (int i = 1; i < len; ++i) {
        cout << " " << map[strSum[i] - '0'];