【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 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,求出数位之和,并用英语表示这个总和的数位的每一位。
【C++代码】
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
int sum=0,digitlen=0;
bool flag=true;
string word[10]= {"zero","one","two","three","four","five","six","seven","eight","nine"};
int digit[10]= {0};
string n;
getline(cin,n);
for(int i=0; i<n.size(); i++) {
sum+=(n[i]-'0');
}
if(sum==0) cout<<word[0]<<endl; //特判sum为0的情况
else {
while(sum) {
digit[digitlen++]=sum%10;
sum/=10;
}
for(int i=digitlen-1; i>=0; i--) { //从高位到低位输出digit数组
if(flag) {
cout<<word[digit[i]];
flag=false;
} else {
cout<<" "<<word[digit[i]];
}
}
cout<<endl;
}
return 0;
}
【Java代码】
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word[] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
int sum=0;
boolean flag=true;
Scanner scan = new Scanner(System.in);
String n = scan.nextLine();
scan.close();
for(int i=0; i<n.length(); i++) {
sum += (n.charAt(i)-'0');
}
String ans = Integer.toString(sum);
for(int i = 0; i < ans.length(); i++) {
if(flag) {
System.out.print(word[ans.charAt(i)-'0']);
flag = false;
} else {
System.out.print(" " + word[ans.charAt(i)-'0']);
}
}
}
}