解题代码:
classSolution {
public:
string find(int n){
switch(n){
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
case 4: return "Four";
case 5: return "Five";
case 6: return "Six";
case 7: return "Seven";
case 8: return "Eight";
case 9: return "Nine";
default: return "";
}
}
string find2(int n){
switch(n){
case 2: return "Twenty";
case 3: return "Thirty";
case 4: return "Forty";
case 5: return "Fifty";
case 6: return "Sixty";
case 7: return "Seventy";
case 8: return "Eighty";
case 9: return "Ninety";
default: return "";
}
}
string find3(int n){
switch(n){
case 1: return "Eleven";
case 2: return "Twelve";
case 3: return"Thirteen";
case 4: return"Fourteen";
case 5: return "Fifteen";
case 6: return "Sixteen";
case 7: return"Seventeen";
case 8: return"Eighteen";
case 9: return"Nineteen";
default: return "";
}
}
string numberToWords(int num) {
string str;
if(num==0)
return "Zero";
if(num>=2000000000){
str+="Two Billion";
num-=2000000000;
if(num>0)
str+=" ";
}
if(num>=1000000000){
str+="One Billion";
num-=1000000000;
if(num>0)
str+=" ";
}
if(num>=1000000){
int a=num/1000000;
num%=1000000;
int c=a%10;
a/=10;
int b=a%10;
a/=10;
if(a!=0){
str+=find(a)+"Hundred";
if(b||c)
str+=" ";
}
if(b>=2){
str+=find2(b);
if(c!=0)
str+=" "+find(c);
}
if(b==1){
if(c!=0)
str+=find3(c);
else
str+="Ten";
}
if(b==0)
str+=find(c);
str+=" Million";
if(num>0)
str+=" ";
}
if(num>=1000){
int a=num/1000;
num%=1000;
int c=a%10;
a/=10;
int b=a%10;
a/=10;
if(a!=0){
str+=find(a)+"Hundred";
if(b||c)
str+=" ";
}
if(b>=2){
str+=find2(b);
if(c!=0)
str+=" "+find(c);
}
if(b==1){
if(c!=0)
str+=find3(c);
else
str+="Ten";
}
if(b==0)
str+=find(c);
str+=" Thousand";
if(num>0)
str+=" ";
}
if(num>=1){
int a=num;
int c=a%10;
a/=10;
int b=a%10;
a/=10;
if(a!=0){
str+=find(a)+"Hundred";
if(b||c)
str+=" ";
}
if(b>=2){
str+=find2(b);
if(c!=0)
str+=" "+find(c);
}
if(b==1){
if(c!=0)
str+=find3(c);
else
str+="Ten";
}
if(b==0)
str+=find(c);
}
return str;
}
};
解题思路:
题目要求返回数字的英文表达。骤眼看去并不难,只需按照数字从高位到低位开始逐个转换即可。但其中有不少容易出错的地方,如11~19的表达,以及空格的表达。容易在不适当的地方缺少或者多出空格,这就需要结合情况进行判断。