PAT (Advanced Level)1005解

因为最近在刷题库,想想就把本人可以想到的解法写到博客里,作为整理归纳。未必是最优解,还请各位高手多多包涵,能够指点指点。

题目要求
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 (≤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

解题思路
逐位输入,然后相加,再转变成英语逐位输出。
注意事项
题目简单,没有什么特殊边界值。
代码部分

#include<stdlib.h>
#include<stdio.h>
main(){
	int A[102]={0};
	int sum=0;
	int j=0;
	char c;
	while((c=getchar())!='\n'){
		A[j]=(int)(c-'0');
		j++;
	} 
	while(j>0){
		j--;
		sum+=A[j];
	}
	//将和倒序存入数组
	for(j=0; j<=100;j++){
		A[j]=sum%10;
		sum=sum/10;
		if(sum==0)
		break;
	} 
	while(j>0){
		switch(A[j]){
			
			case 0:
				printf("zero ");
				break;
			case 1:
				printf("one ");
				break;
			case 2:
				printf("two ");
				break;
			case 3:
				printf("three ");
				break;
			case 4:
				printf("four ");
				break;
			case 5:
				printf("five ");
				break;
			case 6:
				printf("six ");
				break;
			case 7:
				printf("seven ");
				break;
			case 8:
				printf("eight ");
				break;
			case 9:
				printf("nine ");
				break;		
		}			  
		j--;
	}
	//这里因为最后一位输出不能带空格。所以特殊处理
	if(j==0){
		switch(A[j]){
			case 0:
				printf("zero");
				break;
			case 1:
				printf("one");
				break;
			case 2:
				printf("two");
				break;
			case 3:
				printf("three");
				break;
			case 4:
				printf("four");
				break;
			case 5:
				printf("five");
				break;
			case 6:
				printf("six");
				break;
			case 7:
				printf("seven");
				break;
			case 8:
				printf("eight");
				break;
			case 9:
				printf("nine");
				break;
		}
	}
}         
			

运行结果
在这里插入图片描述

发布了12 篇原创文章 · 获赞 3 · 访问量 1331

猜你喜欢

转载自blog.csdn.net/github_38201918/article/details/86533048