- 参考了网友的解题思路。
- 模块化思想。
- 关键是怎么找到想要位得数据, 怎么找到下一位得数据。
- 3位3位添加,最后倒着度。heavy那个变量为size-1。 且索引从1开始。
- 方便对其得思路要用。
- 先处理百分位,在处理有10位的后两位,如果没有十位,那就要单独处理个位。(和百位搭配)
#include<bits/stdc++.h> using namespace std; //模块化思维 //这个函数是为了添加会出现得所有英文字符 string ret_str(int i){ vector<string> rets; //为了好对齐,所以添加了空 rets.push_back(""); //1-10 rets.push_back("one");//rets[1] rets.push_back("two"); rets.push_back("three"); rets.push_back("four"); rets.push_back("five"); rets.push_back("six"); rets.push_back("seven"); rets.push_back("eight"); rets.push_back("nine"); rets.push_back("ten");//rets[10] //11~19 rets.push_back("eleven");//rets[11] rets.push_back("twelve"); rets.push_back("thirteen"); rets.push_back("fourteen"); rets.push_back("fifteen"); rets.push_back("sixteen"); rets.push_back("seventeen"); rets.push_back("eighteen"); rets.push_back("nineteen");//rets[19] rets.push_back("");//空 rets[20] rets.push_back("");// rets[21] 意味着10 //10已经在前面定义过了,若十位为2~9的数字在此输出下标为20+i,为十位的数字 rets.push_back("twenty");//rets[22] rets.push_back("thirty"); rets.push_back("forty"); rets.push_back("fifty"); rets.push_back("sixty"); rets.push_back("seventy"); rets.push_back("eighty"); rets.push_back("ninety");//rets[29] return rets[i]; } //这个函数是为了补单位 string heavy_str(int i){ vector<string> rets; rets.push_back("");//意思一样,方便对齐 rets.push_back("thousand");//rets[1] rets.push_back("million"); //rets[2] rets.push_back("billion"); //rets[3] return rets[i]; } int main(){ long n; while(cin>>n){ if(n>999999999||n<=0){ cout<<"error"<<endl; } vector<int> factor; //每三位存放一次(从后往前) while(n){ int num = n % 1000; factor.push_back(num); n /=1000; } //逆制当前的数组(我们最后输出的时候要逆的输出) reverse(factor.begin(),factor.end()); //确定当前有几个三位数,为输出权重做准备 int sz = factor.size(); int heavy = sz-1; //开始处理 for(int i = 0; i< sz; i++){ int h = factor[i]/100;//得到百位数 //如果取十位数 factor[i]%=100; int t = factor[i]/10;//得到十位数 int o = factor[i]%10;//得到个位数 //先处理百位 if(h!=0 && (t!=0||o!=0)){//111 or 101 cout<<ret_str(h)<<" "<<"hundred"<<" "<<"and"<<" "; } if(h!=0 && t==0&&o==0){//100 cout<<ret_str(h)<<" "<<"hundred"<<" "; } //处理十位 if(t!=0&&t>1&&o!=0){//21 cout<<ret_str(t+20)<<" "<<ret_str(o)<<" "; } if(t!=0&&t>1&&o==0){//20 cout<<ret_str(t+20)<<" "; } if(t!=0&&t<2){//19 cout<<ret_str(10*t+o)<<" "; } //处理个位(没有10位)(此种情况下个位如果为0.直接不管就行) if(t==0&&o!=0){// 1 or 101 cout<<ret_str(o)<<" "; } if(heavy>0){ cout<<heavy_str(heavy)<<" "; } //每输出一次三位数,权重--;!!! heavy--; } cout<<endl; } return 0; }