PAT 甲级 1005 Spell It Right 模拟 字符串

地址  https://pintia.cn/problem-sets/994805342720868352/problems/994805519074574336

题目大意是 输入一个很大的非负整数  0 <= N <=  10100

要求我们把该数的每位上的数字相加,并且按照英文输出每位上的数字

输入样例:
12345
输出样例:
one five

示例解释  因为1+2+3+4+5 =15  所以输出 one five

题目主要考核 数字和字符串的转换
我们输入的字符串(不是数字因为数据范围太大了)逐个转换成数字相加
然后将相加的和拆解成单个的数字 找出对应的字符串 输出即可

        {1,"one"},
        {2,"two"},
        {3,"three"},
        {4,"four"},
        {5,"five"},
        {6,"six"},
        {7,"seven"},
        {8,"eight"},
        {9,"nine"},
        {0,"zero"}    

 

代码

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

int main(){
    string s;
    cin >> s;
    int num = 0;
for(auto& e:s){
    num += e-'0';
}
map<int,string> m{
{1,"one"},
{2,"two"},
{3,"three"},
{4,"four"},
{5,"five"},
{6,"six"},
{7,"seven"},
{8,"eight"},
{9,"nine"},
{0,"zero"}
};
vector<string> ans;
if(num==0){
    cout << "zero" <<endl;
    return 0;
}
while(num!=0){
    int idx = num%10;
    num = num/10;
    ans.push_back(m[idx]);
}
reverse(ans.begin(),ans.end());
for(int i = 0; i<ans.size();i++){
    cout << ans[i];
    if(i!=ans.size()-1){
        cout << " ";
    }
}
cout<<endl;
return 0;
}    

 

posted on 2021-02-10 16:46  itdef  阅读(85)  评论(0编辑  收藏  举报

导航