17.7 给定一个整数,打印该整数的英文描述(例如“One Thousand,Two Hundred Thirty Four”)。
解法:
举个例子,在转换19 323 984时,我们可以考虑分段处理,没三位转换一次,并在适当的地方插入“thousand”(千)和“million”(百万)。也即,
convert(19 323 984)=convert(19)+ “ million ”+convert(323)+“ thousand ”+convert(984);
C++实现代码:
#include<iostream> #include<string> using namespace std; string digits[10]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; string teens[10]={"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; string tens[10]={"Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; string big[10]={"","Thousand","Million"}; string numToString100(int number) { string str; if(number>100) { str+=digits[number/100-1]+" Hundred "; } number%=100; if(number>=11&&number<=19) { return str+teens[number-11]+" "; } else if(number==10||number>=20) { str+=tens[number/10-1]+" "; number%=10; } if(number>=1&&number<=9) { str+=digits[number-1]+" "; } return str; } string numToString(int number) { if(number==0) { return "Zero"; } else if(number<0) { return " Negative "+numToString(-1*number); } int count=0; string str=" "; while(number>0) { if(number%1000) { str=numToString100(number%1000)+big[count]+" "+str; } number/=1000; count++; } return str; } int main() { cout<<numToString(1109); }
时间: 2024-09-30 15:54:24