PAT A1005 Spell It Right (20 分)

mac2026-02-05  0

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

题意:

给定长度不超过101的非负整数,求出各位的和并以英文的格式输出.

思路:

(1)开一个长度大于101的字符数组(为了预留出’\0’的位置)存放键入值; (2)将字符数组各元素-'0’求和; (3)将上述和转化为整型数组,依据该数组各元素的值输出对应的英文.

代码:

#include <cstdio> #include <cstring> char map[10][10]={"zero","one","two","three","four","five","six","seven","eight","nine"}; int main(){ char str[102]; scanf("%s",str); int sum=0; for(int i=0;i<strlen(str);i++){ sum+=str[i]-'0'; } int a[4],len=0; do{ a[len++]=sum%10; sum/=10; }while(sum!=0); //sprintf(a,%d,sum);使用sprintf方法把sum以%d的格式写入a数组,其中a必须是字符数组 for(int i=len-1;i>=0;i--){ printf("%s",map[a[i]]); if(i!=0) printf(" "); } return 0; }

词汇:

non-negative 非负的 consecutive 连续的 long time no see 好久不见

最新回复(0)