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[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; string teens[]={"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; string tens[]={"Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; string big[]={"","Thousand","Million"}; string numToString100(int number)
{
string str;
if(number>)
{
str+=digits[number/-]+" Hundred ";
}
number%=;
if(number>=&&number<=)
{
return str+teens[number-]+" ";
}
else if(number==||number>=)
{
str+=tens[number/-]+" ";
number%=;
}
if(number>=&&number<=)
{
str+=digits[number-]+" ";
}
return str;
}
string numToString(int number)
{
if(number==)
{
return "Zero";
}
else if(number<)
{
return " Negative "+numToString(-*number);
}
int count=;
string str=" ";
while(number>)
{
if(number%)
{
str=numToString100(number%)+big[count]+" "+str;
}
number/=;
count++;
}
return str;
} int main()
{
cout<<numToString();
}