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 (<= 10100).
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的每⼀位相加的和,然后输出和的每⼀位的英⽂读⾳~
解:自己先用了“笨”方法直接按题意写下来,代码看着很冗余。然后参考了大佬的代码, 豁然开朗!加油!!
#include <iostream>
#include <string>
using namespace std;
void func(int a) {
switch (a) {
case 0:cout << "zero"; break;
case 1:cout << "one"; break;
case 2:cout << "two"; break;
case 3:cout << "three"; break;
case 4:cout << "four"; break;
case 5:cout << "five"; break;
case 6:cout << "six"; break;
case 7:cout << "seven"; break;
case 8:cout << "eight"; break;
case 9:cout << "nine"; break;
}
}
int main() {
string s;
int sum = 0;
cin >> s;
for (int i = 0; i < s.length(); i++) {
sum += s[i] - '0';
}
if (sum == 0) {
func(0);
return 0;
}
int b[10], j = 0;
while (sum) {
b[j++] = sum % 10;
sum = sum / 10;
}
func(b[j - 1]);
for (int i = j-2; i >= 0; i--) {
cout << " ";
func(b[i]);
}
return 0;
}
大佬code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string a;
cin >> a;
int sum = 0;
string arr[10] = { "zero","one","two","three","four","five","six",
"seven","eight","nine" };
for (int i = 0; i < a.length(); i++) {
sum += a[i] - '0';
}
string s = to_string(sum);
cout << arr[s[0] - '0'];
for (int i = 1; i < s.length(); i++) {
cout << " " << arr[s[i] - '0'];
}
return 0;
}