[PTA] PAT(A) 1005 Spell It Right (20分)

Problem

Description

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

Each input file contains one test case. Each case occupies one line which contains an $N$($\leq10^{100}$).

## Output

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 ### Sample Input ``` 12345 ``` ### Sample Output ``` one five ```

Solution

Analyse

将一个给出的数,每一位的数值全部加起来,将最终的结果用英文输出。
每一位的数值加起来,可以直接读入一行,然后一个字符一个字符处理,也可以直接读取一个字符,处理一个字符。
最终的结果用英文输出,将每一个数字对应的英文存储在数组中,数字作为下标使用。将最终的结果转换为字符串,然后一个个字符进行处理

Code

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

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

void print_english(int x) {
	string str = to_string(x);
	for (int i = 0; i < str.size(); i++) {
		if (i) cout << " ";
		cout << word[str[i] - '0'];
	}
	cout << endl;
}

int main(void) {
	char ch;
	int sum = 0;
	while (cin >> ch) {
		int x = ch - '0';
		sum += x;
	}
	print_english(sum);
}

Result

posted @ 2019-08-24 09:15  by-sknight  阅读(451)  评论(0编辑  收藏  举报