【PAT(甲级)】1005 Spell It Right

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

解题思路:

N是不大于10^{100},显然极限值会超过int类型,所以我们使用string类型来存储数据。然后每位取出来转换成int类型进行相加。转换成英文字符串时,我采用的是通过%10,每次把最后一位通过switch-case的方式转换成英文,输出的时候会产生相反的情况,所以采用栈(先进后出)的形式将英文进行存储。

其实转换成英文的方式也可以用字符串组加循环的结构例如(这样子代码看起来会少很多):

string a[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
while(result!=0){
     answer.push(a[result%10]);
     result/=10;
}

易错点:

注意特殊情况0的输出;

代码:

#include<bits/stdc++.h>
#include<stack>
using namespace std;

stack<string> answer;//采用栈存储来方便输出 

void turn_E(int a){//将答案用switch-case的方法转换成英文 
	if(a==0)
		answer.push("zero");
	while(a!=0){
		switch(a%10){
			case 0:
				answer.push("zero");
				break;
			case 1:
				answer.push("one");
				break;
			case 2:
				answer.push("two");
				break;
			case 3:
				answer.push("three");
				break;
			case 4:
				answer.push("four");
				break;
			case 5:
				answer.push("five");
				break;
			case 6:
				answer.push("six");
				break;
			case 7:
				answer.push("seven");
				break;	
			case 8:
				answer.push("eight");
				break;
			case 9:
				answer.push("nine");
				break;
		}
		a/=10;
	}
}

void print(){//按照要求来输出英文 
	int k=0;//判断是否为第一个英文字母 
	while(!answer.empty()){
		if(k==0){
			cout<<answer.top();
			answer.pop();
			k++;//是第一个字母后加一即可,相当于让k变量作废了 
		}
		else{
			cout<<" "<<answer.top();
			answer.pop();
		}
	}
}

int main(){
	string N;//采用字符串来读取变量 
	cin>>N;
	int result=0;
	for(int i=0;i<N.size();i++){//用循环来累加每一位数字的和 
		result+=N[i]-'0';
	}

	turn_E(result);	

	print();
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值