前言
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的往期文章