题目链接:http://www.patest.cn/contests/pat-a-practise/1005
题目:
时间限制400 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, YueGiven 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:12345Sample Output:one five
分析:
这一题就是要把输入的一个数字串的每位上的数字相加,然后把和再按每位以英文单词输出,因为是长数字串,所以不能用通常的int等格式存储,我采用的是string存储,然后解析每位的数字,最后累加,然后输出。
记得再创建一个数字到英文单词的string[]或char [][]都可以。
AC代码:
#include<iostream>
#include<string.h>
using namespace std;
char number[10][10] = {
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};//读数的数组
char input[102];
int num[102];
int ans[10];
int main(void){
int i,j,sum;
while(gets(input)){//先按字符串读入数字串,因为可能会很长,其他形式存不下
sum = 0;
for(i = 0; i < 102; i ++){
num[i] = -1;
}
for(i = 0; i < 10; i ++){
ans[i] = -1;
}//初始化
for(i = 0; input[i] != 0; i ++){
num[i] = input[i] - '0';
}//提取各个数位上的数作为加数
for(i = 0; num[i] != -1; i ++){
sum += num[i];
}
int i = 0;
if(sum == 0){
ans[0] = 0;
}
while(sum != 0){
ans[i ++] = sum % 10;//统计sum的各个位,放入ans中
sum /= 10;
}
for(i = 9; i >= 0; i --){
if(ans[i] != -1)break;
}//计算和总共有多少位
while(i >= 0){
if(i == 0){
puts(number[ans[i]]);
}
else{
for(j = 0; number[ans[i]][j] != 0; j ++){
printf("%c",number[ans[i]][j]);
}
printf(" ");
}
i --;
}//格式化输出
}
return 0;
}
——Apie陈小旭