【PAT】PAT Advanced

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

题目大意

求给出的一个数各位数之和,用英文单词隔开,最后没有空格

思路

最大数字为10^100,所以使用string接收。我们可以估计最终结果不超过100 * 9,也就是900,使用递归输出即可。

代码

//
//  main.cpp
//  PAT1005
//
//  Created by 许少钧 on 2019/4/8.
//  Copyright © 2019年 许少钧. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
string a[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
void f(int n){
    int next = n / 10;
    if(next > 0){
        f(next);
        printf("%c", ' ');
    }
    cout << a[n % 10];
}
int main(int argc, const char * argv[]) {
    int n = 0;
    string s;
    cin >> s;
    const unsigned long l = s.size();
    for(int i = 0; i < l; i++){
        n += s[i] - '0';
    }
    if(n == 0) printf("zero");
    else f(n);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a617976080/article/details/89089570
今日推荐