PAT甲级(Advanced Level)----1005

1005 Spell It Right (20point(s))

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 ( ≤ 1 0 100 ) N\left(\leq 10^{100}\right) 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

这个题目就是将12345,输入的数字每一位相加,然后将结果用英文打印出来,按位打印,zero、one、two、three、four、five、six、seven、eight、nine。

这里参考了柳神的在1001里面的做法。(1001做完的时候学到的)
直接读取字符串,然后用string[INDEX] - ‘0’ 来获取每一位的数字。
这里sum 声明为int就完全够了。

再用to_string()将sum转为string。
然后打印。
打印要注意一下,最后一个数字后面没有空格。

#include 
using namespace std;
int main()
{
    string number;
    cin>>number;
    int sum = 0;
    int len = number.length();
    for (int i = 0; i < len; i++) {
        sum+= (number[i] - '0');
    }
    string res = to_string(sum);
    int length = res.length();
    for(int i  = 0; i<length; i++){
        int temp = res[i] - '0';
        switch(temp)
        {
            case 0:
                cout<<"zero";
                break;
            case 1:
                cout<<"one";
                break;
            case 2:
                cout<<"two";
                break;
            case 3:
                cout<<"three";
                break;
            case 4:
                cout<<"four";
                break;
            case 5:
                cout<<"five";
                break;
            case 6:
                cout<<"six";
                break;
            case 7:
                cout<<"seven";
                break;
            case 8:
                cout<<"eight";
                break;
            case 9:
                cout<<"nine";
                break;
        }
        if(i != length - 1) cout<<" ";
    }
    return 0;
}

你可能感兴趣的:(笔记,数据结构与算法)