题目
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
思路
本题较为简单,只需知道
1,字符怎么转换为int即可,直接用int类型强转,得到字符ascii,再-48即是对应的数字。
2,数字怎么转换为字符串to_string(int a)
,方便得到求和结果的每一数位。当然也可以用求余的方法得出。
3,扩展——字符串怎么转换为数字atoi(s.c_str())
,其中s为字符串。
这一题和1001题其实差不多,就是多了一个map
stl库的使用
PAT甲级题库 1001 A+B Format (20 分)
题解
#include<iostream>
#include<string>
#include<map>
using namespace std;
void inio(map<int,string>& a)
{
a[0] = "zero";
a[1] = "one";
a[2] = "two";
a[3] = "three";
a[4] = "four";
a[5] = "five";
a[6] = "six";
a[7] = "seven";
a[8] = "eight";
a[9] = "nine";
}
int main()
{
string s;
cin >> s;
int ans=0;
for (int i = 0; i < s.size(); i++)
{
ans += (int)s[i]-48;
}
string s1 = to_string(ans);
map<int, string> ItoE;//数字转英文map
inio(ItoE);
cout << ItoE[s1[0]-48];
for (int i = 1; i < s1.size(); i++)
{
cout << ' '<<ItoE[s1[i]-48];
}
}