每日算法题 Day5 of PAT 1005 Spell It Right (20分)

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

今天做的1005 、1006两道题都挺简单的,特别是在我掌握了vector类以及sort函数的使用之后,不用再考虑一些空间分配问题以及排序算法选择问题,省去了我不少烦恼。

而眼下这道1005就是想让我们将屏幕上的数字每一位相加,然后再从高位到低位顺次输出该位字母的英文单词

Attention:

  • 挨个读入字符需要用到cin.get()函数,这个函数本身没什么,但是顺带一提的是,在PAT的官方文档上说明了的是itoa()、gets() 这两个函数因为安全原因被禁用掉了,这一点是需要注意的,尽量找替代方法
  • 然后就是按照常规我们要注意一下输入输出,老规矩,输出还是最后不能有空格,而输入,乍一眼看过去吓我一跳,10的100次方,上一秒我还在想int类型最大不过2的10次方级,下一秒我就醒悟了,为了方便运算,我们肯定是以字符的形式从屏幕读取数字,而10的100次方,充其量不过是个长度为101的字符串,也就没什么好说的了

Details:

  • 既然要输出数字对应的字母,那就可以用string数组做一个映射
  • 要注意的是,因为数字大小原因我们读入的是字符串,一个一个的是字符,但我们需要各位相加,那就涉及到一个字符与数字的转换,由于编码格式是ASCII,那么只要将字符的ASCII码值减去48,就能得到对应的数字了,即:(‘k’)ASCII - 48 = k(k=1,2,3,…,9)

Code:

#include <bits/stdc++.h>
using namespace std;
int main(){
	char ch;
	string numToString[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
	int count=0;
	vector<int> digits;
	ch=cin.get();
	while(ch!='\n'){
		count+=(ch-48);
		ch=cin.get();
	}
	if(count==0){
		cout<<"zero";
		return 0;
	}
	while(count!=0){
		digits.push_back(count%10);
		count/=10;
	}
	for(std::vector<int>::reverse_iterator it=digits.rbegin();it<digits.rend();it++){
		if(it+1<digits.rend())
			cout<<numToString[*it]<<" ";
		else
			cout<<numToString[*it];
	}
	return 0;
}

Summary and harvest

(for my current level)

1.迭代器
for (std::vector::iterator it = vecTest.begin(); it != vecTest.end(); ++it)
{
tempNum = *it;
}
2.C++11 新增关键字auto
for (auto it : vecTest)
{
tempNum = it;
}
3.对C念念不舍的童鞋们习惯的数组写法
for (size_t i = 0; i < maxCount; i++)
{
tempNum = vecTest[i];
}

for(std::set::reverse_iterator it2=myvec.rbegin();it2 != myvec.rend();++it2)
{
cout<<*it2<<endl;
}

get() 是 istream 类的成员函数,它有多种重载形式(请猛击这里了解详情),不过本文只介绍最简单最常用的一种:
int get();
此函数从输入流中读入一个字符,返回值就是该字符的 ASCII 码。如果碰到输入的末尾,则返回值为 EOF。
EOF 是 End of File 的缩写。istream 类中从输入流(包括文件)中读取数据的成员函数,在把输入数据都读取完后再进行读取,就会返回 EOF。EOF 是在 iostream 类中定义的一个整型常量,值为 -1。
get() 函数不会跳过空格、制表符、回车等特殊字符,所有的字符都能被读入。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值