PAT甲级 1005 Spell it Right (哈希表)

前言

1005 这道题目主体是一个高精度问题。

题目概述

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

AC代码

#include<iostream>
#include<string>
#include<unordered_map>
#include<vector>
using namespace std;

unordered_map<int, string> um{{0, "zero"}, {1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}, {5, "five"}, {6, "six"}, {7, "seven"}, {8, "eight"}, {9, "nine"}};


vector<int> add(vector<int> A, int b)
{   
    A[0] += b;
    int t = 0;
    while(A[t] >= 10)
    {
        if(t == A.size() - 1)
        {
            A.push_back(A[t] / 10);
            A[t] %= 10;
        }
       else
       {
           A[t + 1] += (A[t] / 10);
           A[t] %= 10;
       }
        ++t;
    }
    return A;
}

vector<int> A;
string a;
bool f = true;
int main()
{
    A.push_back(0);
    getline(cin, a);
    for(auto c : a)
    {
        A = add(A, c - 48);
    }
    
    for(int i = A.size() - 1; i >= 0; --i)
    {
        int b = A[i];
        
        if(f)
        {
            cout << um[b];
            f = false;
        }
        else cout << " " << um[b];
    }
    
    return 0;
}

分析思路

1.题意大概是给出一个数字,要求把这个数字的每个位置上的数字加起来得到一个和,然后把这个和的数字按照从高位到低位的方式输出其英文。

2.分析数据,最大数字是会有100位数字,不需要用高精度! 我这里写的是高精度加法的原因是因为一开始看错了hhh,不过也ok,这样的代码如果数据更强也是可以过的。
普适性更强一点(
3.输出英文单词的时候为了方便,可以用一个hash表来做。

文末广告

学习算法和数据结构真的是个很累的过程,不会做只能求助于题解。 因为写代码这个东西基本上是千人千面。同时网络上搜到的题解很多要么用到的是自己还没学到的知识,看不懂;要么内核过于简陋,只能糊弄当前题目,不具有普适性。
如果你是一个喜欢做洛谷,ACwing和PTA的题目的同学,欢迎关注我的博客,我主要在这三个平台上做题,认为有价值和有难度的题目我会写题解发布出来。

TreeTraverler的往期文章

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

102101141高孙炜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值