PAT甲级(Advanced Level)练习题 Spell It Right

题目描述

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.

输入描述:

Each input file contains one test case. Each case occupies one line which contains an N (<= 10100).

输出描述:

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.

输入例子:

12345

输出例子:

one five

题目分析:

简单的输出问题,计算每个位的数字和,然后把每个位从后往前移到栈stack里,最后从栈中按顺序打印出数字即可。

代码实现(C++版本)

#include <iostream>
#include <stack>
using namespace std;

string getString(int a){
    switch (a){
    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 "error";
}

int main()
{
    string a;
    cin >>a;
    long answer = 0;
    for(unsigned long i =0;i<a.length();i++){
        answer += a[i]-'0';
    }
    stack <string> sta;
    while(answer!=0){
        int temp = answer%10;
        string get = getString(temp);
        sta.push(get);
        answer /= 10;
    }
    string first = sta.top();
    sta.pop();
    cout << first;
    while(!sta.empty()){
        cout <<" "<< sta.top();
        sta.pop();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37221167/article/details/88750249