当前位置: 代码迷 >> 综合 >> [PAT A1005]Spell It Right
  详细解决方案

[PAT A1005]Spell It Right

热度:45   发布时间:2023-12-15 06:22:56.0

[PAT A1005]Spell It Right

题目描述

1005 Spell It Right (20 分)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.

输入格式

Each input file contains one test case. Each case occupies one line which contains an N (≤10?100??).

输出格式

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.

输入样例

12345

输出样例

one five

解析

  1. 题目题意很好理解,就是输入一个数,计算它们各位之和,并且以英文字母的形式输出各位,例如输入12345,那么各位相加就是1+2+3+4+5=15,输出就是one(1)five(5)
  2. 这道题目解决起来不难,主要是要掌握各种工具,要能手到擒来,其中最最最最重要的就是to_string()函数的使用,使用这个函数可以帮我们节省不少的时间,关于to_string()的使用方法可以参考我的博客:

工欲善其事必先利其器——盘点PAT中非常好用的工具(持续更新)
下面贴代码:

#include<iostream>
#include<string>
using namespace std;
string hashTable[10] = {
     "zero","one","two","three","four","five","six","seven","eight","nine" };
int main()
{
    int sum = 0;string str;cin >> str;for (int i = 0; i < str.length(); i++)sum += str[i] - '0';str = to_string(sum);for (int i = 0; i < str.length(); i++) {
    cout << hashTable[str[i] - '0'];if (i != str.length() - 1) cout << " ";}return 0;
}

水平有限,如果代码有任何问题或者有不明白的地方,欢迎在留言区评论;也欢迎各位提出宝贵的意见!