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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章