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 <cstdio>
#include <cstring>
char eng[10][10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int main(){
// 用整型变量录入数据
/*long long a;
scanf("%lld", &a);
int sum = 0;
while(a != 0){
sum += a % 10;
a = a / 10;
}
printf("%d", sum);*/
// 用数组录入数据
char str[110];
scanf("%s", str);
int len = strlen(str);
int res = 0;
for(int i = 0; i < len; i++){
res += (str[i]-'0');
}
if(res == 0){
printf("%s", eng[0]);
}else{
// printf("%d", res);
// 把数字之和存到数组中
int num[100];
int i = 0;
while(res != 0){
num[i] = res % 10;
res = res / 10;
i++;
}
// 逆序输出数组,对应英文字母
for(int j = i-1; j >= 0; j--){
printf("%s", eng[num[j]]);
if(j != 0)
printf(" ");
}
}
return 0;
}
第一次代码提交出现一个测试点答案错误,看《算法笔记》后发现是忽略了如果 sum 为 0 的情况下,直接输出0的情况。
把 sum 写入数组的最简单方法:(sprintf)
sprintf(digit, "%d", sum);
含义:将 sum 按 %d 的格式写到数组 digit[ ]中去。digit 必须是字符型数组。