PAT-A 真题- 1005. Spell It Right

发布于 / PAT-甲级 / 0 条评论

原题干:

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

题目大意:

给定一行数,要求求出这一行所有数字之和,并将每一位使用英文打印。每个单词用空格分离,末尾不得有多余空格。

这道题可以直接使用字符串来做。因为题目给的最大的数字是10100所以最大的结果也就是三位数。三个if就足矣。但是要切记注意十位数为0的判断。下面是一个经典错解

#include <iostream>
using namespace std;

int main(){
    string input, map[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    cin >> input;
    int cal = 0;
    for(int i = 0; i < input.length(); i++){
        cal += (input[i] - '0');
    }
    int notfirst = 0;
    if(cal >= 100){
        int output = cal / 100;
        if(notfirst++) cout << " ";
        cout << map[output];
        cal %= 100;
    }
    if(cal >= 10){
        int output = cal / 10;
        if(notfirst++) cout << " ";
        cout << map[output];
        cal %= 10;
    }
    if(notfirst++) cout << " ";
    cout << map[cal];
    cout << endl;
    return 0;
}

这样提交的话第四个测试点不会通过。比如你输入一个"999999999999"(12个9),得到的结果应该是108(one zero eight),但是在处理完百位后,cal只剩下08,计算机认为08==8,就造成了错误。正确的答案如下:

#include <iostream>
using namespace std;

int main(){
    string input, map[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    cin >> input;
    int cal = 0;
    for(int i = 0; i < input.length(); i++){
        cal += (input[i] - '0');
    }
    int notfirst = 0, hundred = 0;
    if(cal >= 100){
        hundred++;
        int output = cal / 100;
        if(notfirst++) cout << " ";
        cout << map[output];
        cal %= 100;
    }
    if(cal >= 10 || hundred){
        int output = cal / 10;
        if(notfirst++) cout << " ";
        cout << map[output];
        cal %= 10;
    }
    if(notfirst++) cout << " ";
    cout << map[cal];
    cout << endl;
    return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题- 1005. Spell It Right
目前还没有评论,快来抢沙发吧~