题目:
给定一个整数,打印该整数的英文描述。(例如:“One Thousand, Two Hundred Thirty Four”)
思路:
每三位转换一次,在适当位置插入million,thousand。即:
convert(19 323 984)=convert(19)+" million, "+convert(323)+" thousand "+convert(984)
代码:
#include<iostream> using namespace std; string digits[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; string teens[]={"Eleven","Twelve","ThirTteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; string tens[]={"Ten","Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"}; string bigs[]={"","Thousand,","Million,"}; string numToEnglish100(int num); string numToEnglish(int num){ if(num==0) return "Zero"; else if(num<0){ return "Negative " + numToEnglish(-1*num); } int count=0; string str=""; while(num>0){ if(num%1000!=0){ str=numToEnglish100(num%1000)+bigs[count]+" "+str; } num/=1000; count++; } return str; } string numToEnglish100(int num){ string str=""; if(num>=100){ str+=digits[num/100-1]+" Hundred "; num%=100; } if(num>=11 && num<=19){ return str+teens[num-11]+" "; } else if(num==10 || num>=20){ str+=tens[num/10-1]+" "; num%=10; } if(num>=1 && num<=9) str+=digits[num-1]+" "; return str; } int main(){ int num; while(cin>>num){ cout<< numToEnglish(num) <<endl; } return 0; }