PTA1005 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
题目分析:
将字符串相加的结果用英文表达出来。
用tot表示当前sum的最高位数字,step统计位数+最后输出空格。
代码如下:
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
int main()
{
string s[]={"zero","one","two","three","four","five","six","seven","eight","nine"};
string str;
cin>>str;
long long int sum=0;
for (int i = 0; i < str.length(); i++)
{
sum+=str[i]-48;
}
long long int tot=sum;
int step=1;
while (tot>9)
{
tot/=10;
step++;
}
//cout<<sum<<' '<<step<<endl;
while (sum>=0)
{
tot=sum;
while (tot>9)
{
tot/=10;
//cout<<tot<<endl;
}
switch (tot)
{
case 1:cout<<s[1];break;
case 2:cout<<s[2];break;
case 3:cout<<s[3];break;
case 4:cout<<s[4];break;
case 5:cout<<s[5];break;
case 6:cout<<s[6];break;
case 7:cout<<s[7];break;
case 8:cout<<s[8];break;
case 9:cout<<s[9];break;
case 0:cout<<s[0];break;
default:
break;
}
sum-=tot*pow(10,--step);
if(step>0) cout<<' ';
else break;
}
return 0;
}
总结
两个字符串利用string类非常方便,利用位数输出空格,一次通过。