PTA-1005—— Spell It Right

本文介绍了一个处理大整数加法并将其各数位之和以英文单词形式输出的C++程序实现。文章详细展示了如何通过逐位累加的方式处理大整数,并在遇到进位时进行相应的调整,最后将得到的数位和转换成英文单词输出。特别注意了输入为0的特殊情况。

题目:

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 (≤).

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

题目分析:

 

加数只有1位的大整数加法,但要考虑输入为0的特殊情况

 

代码:

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 int ans[110];
 5 string number[10]={"zero","one","two","three","four",
 6                     "five","six","seven","eight","nine"};
 7 string s;
 8 int main(){
 9     cin>>s;
10     memset(ans,0,sizeof(ans));
11     for(int i=0;i<s.length();i++){
12         ans[0]+=s[i]-'0';
13         for(int j=0;j<s.length();j++){
14             if(ans[j]>=10){
15                 ans[j]-=10;
16                 ans[j+1]+=1;
17             }
18         }
19     }
20     bool flag=false;
21     for(int i=s.length()-1;i>=0;i--){
22         if(ans[i]!=0||flag){
23             flag=true;
24             if(i==0){
25                 cout<<number[ans[i]];
26             }else{
27                 cout<<number[ans[i]]<<" ";
28             }
29         }
30     }
31     if(!flag){            //一个特殊情况需要考虑:当输入为0时 
32         cout<<"zero";
33     }
34     return 0;
35 } 

 

 

转载于:https://www.cnblogs.com/orangecyh/p/10274454.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值