PAT (Advanced Level)1005解

本文提供了一道编程题“1005SpellItRight”的解题思路及代码实现。题目要求对非负整数N的每一位进行求和,并用英文单词输出每位的和。代码通过逐位读取、累加并转换成英文输出,适用于编程初学者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题目要求
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;
		}
	}
}         
			

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值