1005 Spell It Right【PAT (Advanced Level) Practice】

1005 Spell It Right【PAT (Advanced Level) Practice】

原题链接:预览题目详情 - 1005 Spell It Right (pintia.cn)

1.题目原文

Given a non-negative integer N N N, your task is to compute the sum of all the digits of N N 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 N N ( ≤ 1 0 100 \le 10^{100} 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

2. 题目翻译

给定一个非负整数 N N N,你的任务是计算 N N N的所有数字的和,并以英语输出和的每个数字。

输入规范:

每个输入文件包含一个测试用例。每个案例占据一行,其中包含一个 N N N ≤ 1 0 100 \le 10^{100} 10100)。

输出规范:

对于每个测试用例,在一行中输出和的数字的英文单词。两个连续单词之间必须有一个空格,但在行末不能有额外的空格。

示例输入:

12345

示例输出:

one five

3.解题思路

3.1题目分析

计算一个非负整数的各位数字之和,并以英文单词输出这个和的每一位数字。

3.2基本思路

将整数转换为字符串,然后遍历字符串计算各位数字之和,并将和的每一位数字以英文单词输出。

3.3详解步骤

  1. 定义函数 i_to_s:

    • 将整数转换为字符串,存储在字符数组中。
  2. 主函数 main:

    • 从标准输入读取一个字符串表示的数字。
    • 计算各位数字之和。
    • 调用函数将和转换为字符串。
    • 输出各位数字的英文单词,用空格分隔,最后换行。

4.参考答案

#include <stdio.h>
#include <string.h>

// 将整数转换为字符串
void i_to_s(int sum, char n[]) {
    
    
    int d, i;

    i = 0;
    // 取最低位的数字,并将其转换为字符存入数组
    d = sum % 10;
    sum /= 10;
    while (sum) {
    
    
        n[i++] = d + '0';
        d = sum % 10;
        sum /= 10;
    }
    n[i++] = d + '0';
    n[i] = '\0';  // 字符串末尾加上'\0'表示字符串结束
}

int main() {
    
    
    char n[102];
    int sum, i;

    scanf("%s", n);
    sum = 0;
    // 计算输入数字的各位数字之和
    for (i = 0; n[i] != '\0'; i++)
        sum += n[i] - '0';

    i_to_s(sum, n);
    i = strlen(n) - 1;

    // 将和的每一位数字以英文单词输出
    while (i != -1) {
    
    
        switch (n[i--] - '0') {
    
    
            case 0: printf("zero"); break;
            case 1: printf("one"); break;
            case 2: printf("two"); break;
            case 3: printf("three"); break;
            case 4: printf("four"); break;
            case 5: printf("five"); break;
            case 6: printf("six"); break;
            case 7: printf("seven"); break;
            case 8: printf("eight"); break;
            case 9: printf("nine"); break;
        }
        if (i != -1)
            printf(" ");
        else
            printf("\n");
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40171190/article/details/134746775