PAT Advanced 1005. Spell It Right

发布时间 2023-05-03 10:17:53作者: 十豆加日月

PAT Advanced 1005. Spell It Right

1. Problem Description:

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.

2. Input Specification:

Each input file contains one test case. Each case occupies one line which contains an \(N\) (\(≤10^{100}\)).

3. 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.

4. Sample Input:

12345

5. Sample Output:

one five

6. Performance Limit:

Code Size Limit
16 KB
Time Limit
400 ms
Memory Limit
64 MB

思路:

按照题意编写即可,注意非负整数 \(N \le 10^{100}\),普通整数类型存不下,需要存为字符串类型。C++有了string类型就很舒服,计算每一位之和并按要求输出,这里还需要注意指向字符串常量的char指针数组digits需要加上const修饰,不然编译器会报警告。

My Code & Result:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string num;
    int sum=0;
    const char *digits [] = {"zero", "one", "two", "three", "four", "five",
                        "six", "seven", "eight", "nine"};
    
    cin >> num;
    
    for(const auto &w: num)
    {
        sum += w-'0';
    }

    string res = to_string(sum);

    for(unsigned int i=0; i<res.size(); ++i)
    {
        if(!i) printf("%s", digits[res[i]-'0']);
        else printf(" %s", digits[res[i]-'0']);
    }
    printf("\n");
    
    // cout << res << endl;

    return 0;
}
Compiler
C++ (g++)
Memory
440 / 65536 KB
Time
4 / 400 ms