【PAT甲级 - C++题解】1005 Spell It Right

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1005 Spell It Right (pintia.cn)
🔑中文翻译:拼写正确
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

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

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

思路

  1. 用字符串 x 读入数字,然后计算每一位数的总和。注意,这里有个小技巧,计算字符串的每一位数可以通过 i - '0' 来求。
  2. 将要用到的单词用数组存起来,就不用反复 if else 了。
  3. 对总和 sum 进行字符串转化得到 res ,然后对 res 从前往后遍历,将数字转换成对应的单词并输出。这里同样要注意的是,在 PAT 中,对于输出的空格把控很严格,行尾不能有多余空格。所以我们可以先输出一个答案,然后再对后续答案进行统一化输出。

代码

#include<bits/stdc++.h>
using namespace std;

int main()
{
    string x;
    cin >> x;

    //计算每一位数的总和
    int sum = 0;
    for (auto i : x)   sum += i - '0';

    //将字符串用数组存起来,方便使用
    string words[10] = { "zero","one","two","three"
        ,"four","five","six","seven","eight","nine" };

    //将结果进行字母转换
    string res = to_string(sum);
    cout << words[res[0] - '0'];
    for (int i = 1; i < res.size(); i++)
        cout << " " << words[res[i] - '0'];

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值