1005 Spell It Right (20 分)

1. 题目

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

Sample Output:

one five

2. 题意

计算输入数字的每一位的和(例:12345,每一位的和为1+2+3+4+5=15),并将结果的每一位用英文形式输出(例:20,输出结果为two zero)。

3. 思路——字符串

根据题目N≤\(10^{100}\),intlong long型大小不足以容纳, 这里使用string类型存储输入信息,遍历输入的字符串,每一位ch,根据ch-'0'将字符转化为0-9的整数形式,并将每一位相加,相加结果根据除10取余法将每一位取出,并输出每一位的英文形式即可。

4. 代码

#include <iostream>
#include <string>
#include <vector>

using namespace std;

// 将数字0-9转化为zero-nine 
string ntos(int x)
{
    switch (x)
    {
        case 0: return "zero";
        case 1: return "one";
        case 2: return "two";
        case 3: return "three";
        case 4: return "four";
        case 5: return "five";
        case 6: return "six";
        case 7: return "seven";
        case 8: return "eight";
        case 9: return "nine";
    }
    return "";
}

int main()
{
    string s;
    cin >> s;
    int sum = 0;
    vector<int> res;
    // 计算s每一位相加起来的和 
    for (int i = 0; i < s.length(); ++i)
        sum += s[i] - '0';
    if (sum == 0) res.push_back(0);
    // 除10取余法,将数sum的每一位取出 
    while (sum)
    {
        res.push_back(sum % 10);
        sum /= 10;
    }
    // 通过ntos函数将数sum的每一位转化为英文形式输出 
    for (int i = res.size() - 1; i >= 0; --i)
    {
        if (i != 0) cout << ntos(res[i]) << " ";
        else cout << ntos(res[i]) << endl;
    }
    return 0;
}
上一篇:java项目学习报错


下一篇:Spring框架的常见错误