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

题目解读

题目很简单,给出一个正整数N,把它每个位置上的数组加起来得到一个新的整数M,要求输出M每个位置上的数字用对应的英文代替,并用空格隔开

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

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

然后数字转成英文好办,用一个char数组作为映射表即可。

代码

题目比较简单,直接看吧,没什么难的,注意一下最后的输出末尾不要有多余空格。

#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'];
    }
}