PAT 1005 Spell It Right (20分) 字符数组做映射

本文介绍了一个简单的编程任务,即接收一个大数(可达10^100),将其各位数字相加得到的新数以英文形式输出,每个数字间用空格隔开,且末尾无多余空格。通过使用字符串而非数值类型来处理大数,避免了数据溢出问题。代码中利用映射表将数字转换为英文单词,实现了题目的要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

题目解读

题目很简单,给出一个正整数N,把它每个位置上的数组加起来得到一个新的整数M,要求输出M每个位置上的数字用对应的英文代替,并用空格隔开

也就是 123 要输出成 one two three ,并且最后面不能有多余空格。

注意: N 最大可以取到 10100,所以千万不要用 int,long long 。。。用 string !!!

然后数字转成英文好办,用一个char数组作为映射表即可。

代码

题目比较简单,直接看吧,没什么难的,注意一下最后的输出末尾不要有多余空格。

#include <iostream>
using namespace std;

int main() {
    // int 无法存储
    string strNum;
    cin >> strNum;
    int len = strNum.length();
    int sum = 0;
    // 每一位加起来
    for (int i = 0; i < len; ++i) {
        sum += (strNum[i] - '0');
    }
    // 结果转为字符串,每一位用英文表示
    string strSum = to_string(sum);
    // 映射表
    string map[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    // 输出第一个位置
    cout << map[strSum[0] - '0'];
    // 输出 空格 其他位置,这样可以满足输出格式要求,最末尾不能有多余空格
    len = strSum.length();
    for (int i = 1; i < len; ++i) {
        cout << " " << map[strSum[i] - '0'];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值