1. 程式人生 > >pat訓練題--1005 Spell It Right(20 分)

pat訓練題--1005 Spell It Right(20 分)

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.

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,你的任務是計算所有數字的總和N,用英語輸出總和的每一位數。

輸入規格:
每個輸入檔案包含一個測試用例。每個案例佔一行包含一個N(≤10
​100).

輸出規格:
對於每個測試用例,在一行中輸出英文單詞中總和的數字。兩個連續的單詞之間必須有一個空格,但在一行的末尾沒有多餘的空格。

樣本輸入:
12345
樣本輸出:
one five

本題的考點就再於去怎麼處理這麼大的資料相加,如果直接相加的話,long型也會溢位

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
void print(int i)
{
	switch (i)
	{
	case 0:printf("zero"); break;
	case
1:printf("one"); break; case 2:printf("two"); break; case 3:printf("three"); break; case 4:printf("four"); break; case 5:printf("five"); break; case 6:printf("six"); break; case 7:printf("seven"); break; case 8:printf("eight"); break; case 9:printf("nine"); break; } } int main() { char ch; vector<int>sum; sum.push_back(0); while ((ch = getchar()) != '\n') { sum[0] += ch - '0'; //==========================================核心演算法 if (sum[0] >= 10) { int k = 0; for (int i = 0; i < sum.size()-1; i++) { sum[i + 1] += sum[i] /10; //大資料加法實現 sum[i] = sum[i] % 10; } if (sum[sum.size() - 1] >= 10) { sum.push_back(sum[sum.size() - 1] / 10); sum[sum.size() - 2] = sum[sum.size() - 2] % 10; } } //=================================================== } bool flag = false; for (int i = sum.size() - 1; i >= 0; i--) { if (flag) { printf(" "); } flag = true; print(sum[i]); } return 0; }