题目内容
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
一、题干大意
给出一个非负的整数,范围在0~10^100,需要你将所有位上的字符加起来,然后用英语输出。
二、题解要点
- 简单来说就是先把输入的数一个个分开加起来,然后把最后加起来的总和再分开,用英语输出
三、具体实现
#include <iostream>
#include <string>
using namespace std;
string turnEnglish(int num);
int main() {
string n; //用于接收输入的字符串,因为数字过大,如果采用其他类型测试点6会过不了
int sum = 0; //用来计算输入数字的总和
string theResult = ""; //最后输出的结果
cin >> n;
/*计算输入数字的各位相加总和*/
for (int i = 0; i < n.length(); ++i) {
sum += (n[i] - '0');
}
/*将总和转化为英语*/
do {
theResult = turnEnglish((sum % 10)) + " " + theResult;
sum /= 10;
} while (sum != 0);
/*由于每次转化都会有一个空格,所以最后需要去掉这个空格*/
theResult = theResult.substr(0, theResult.length() - 1);
cout << theResult << endl;
}
/***
* 用于数字转英语的函数
* @param num
* @return
*/
string turnEnglish(int num) {
switch (num) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
case 4:
return "four";
case 5:
return "five";
case 6:
return "six";
case 7:
return "seven";
case 8:
return "eight";
case 9:
return "nine";
default:
return "";
}
}
总结
难度比较小。但是要注意以下几点:
- 这个数字的范围比较大,不能用数字类型的变量去接收;
- 如果输入了0也要做处理;
- 不要拼错单词。