PATA1005 Spell It Right (20分)

PATA1005 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 (≤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

题目的意思是,给你一串数字,每个数字加起来的和转化成英文的one,two,three等等

首先我们要思考这个怎么输入。

首先设定包括one,two,three…的一个常量数组

const string number[] = {"zero", "one", "two", "three", "four", "five", "six","seven", "eight", "nine"};

之所以这样做,我们可以发现,这个常量数组的下标和值是对应的,例如number[0]对应zero。在后期输出时候可以很方便的通过下标输出对应的英文值。

再看到,输入是一串数字,我们可以考虑把它看成是一串字符串的输入,这样方便以字符串的下标开始一个个求和。求出的和可以转成字符串,从左往右以字符串下标的顺序读取求出的和的每一位,再对应事先准备好的常量数组输出。

例如和是15,这个结果转成字符串后,下标0的值1对应常量数组下标1one;

下标1的值5对应常量数组下标1five

用代码表示就是:

number[strsum[i]-'0']
//number是常量数组
//strsum是和的结果转化成的字符串
//之所以-'0'是因为 求和结果的字符串 里的值类型是char,让它与'0'相减能够得到int型的值。'9'-'0'是int 型的9,'7'-'0'是int型的7等等

注意到输出结果的末尾不能有空格,那么我们可以在字符串下标循环的时候,判断循环的值是否等于字符串长度-1(字符串下标最远处是字符串长度-1),如果不等于那么输出空格,等于就不输出空格。这样就解决了。

大致思路就是这样。接下来放代码

#include <iostream>
#include <string>
using namespace std;
const string number[] = {"zero", "one", "two", "three", "four", "five", "six","seven", "eight", "nine"};
int main()
{
    string str;
    int sum = 0;
    cin >> str;	//输入数据
    for(int i = 0;i<str.length();i++) {
        sum += str[i]-'0';//求出输入数据的和
    }
    string strsum = to_string(sum);
    for(int i = 0;i<strsum.length();i++) {//求和结果字符串循环
        cout << number[strsum[i]-'0'];//输出常量数组
        if (i != strsum.length()-1)//空格控制
            cout << " ";
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章