A1005 Spell It Right (20 point(s))

数字各位相加和转字符

1. 原文

原题

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:

1
12345

Sample output:

1
one five

2. 解析

将正整数N的每位数相加,和以英文输出

如:12345 -> 1+2+3+4+5=15 -> one five

Solution:

以字符串的形式输入,防止数字过大,int/long long整型越界。

加每一位的字符 str[i]-‘0’

取和的每位数值后输出

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<cstdio>
char str[110];
int num[110]={};
char ans[][7]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int main()
{
scanf("%s",str);
int sum=0;
for (int i = 0; str[i] != '\0'; ++i)
{
sum+=str[i]-'0';
}
if (sum==0)
{
printf("%s\n",ans[0]);
return 0;
}
//printf("%d\n",sum);
int idx=0;
while(sum){
num[idx++]=sum%10;
sum/=10;
}
printf("%s",ans[num[idx-1]]);
for (int i = idx-2; i >= 0 ; i--)
{
printf(" %s",ans[num[i]]);
}
printf("\n");
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1005/
  • 发布时间: 2019-09-03 12:36
  • 更新时间: 2021-10-29 13:58
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!