题解 | #学英语C++#
学英语
http://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc
用C++实现“学英语”
这道题不难,就是很烦,需要注意的细节很多,思路和注释很详细的,各位看官慢用
思路:
1.接收数据
2.三位,三位分开,不够3的倍数,前方补0
3.进行三位数的英文输出
4.正确添加权重
5.控制好输出格式
#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.push_back(""); //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) { //两个rets不一样,不要搞混了 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 num; //获取当前输入整数 while(cin>>num) { //非法数字输出error if(num>999999999 || num<0) { cout<<"error"<<endl; continue; } int num1=num; //每三位存放一次(从后往前) vector<int> factor; while(num1) { int n = num1%1000; factor.push_back(n); num1/=1000; } //逆制当前的数组 reverse(factor.begin(), factor.end()); //确定当前有几个三位数,为输出权重做准备 int sz=factor.size(); int heavy=sz-1; for(int i=0;i<sz;i++) { int flag=factor[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 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)<<" "; if(h==0 && t==0&&o!=0) //1 cout<<ret_str(o)<<" "; if(h!=0 && t==0 && o!=0) //101 cout<<ret_str(o)<<" "; //long a=pow(1000,heavy); //int flag = num%a; if(heavy>0 && flag)//输出权重(当前三位数不为0时才能输出权重) { cout<<heavy_str(heavy)<<" "; } //每输出一次三位数,权重--;!!! heavy--; } cout<<endl; } }