输入:num = 12345 输出:"Twelve Thousand Three Hundred Forty Five"
输入:num = 1234567 输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
输入:num = 1234567891 输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
class Solution {
String[] low = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
String[] mid = {"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen",
"Seventeen", "Eighteen","Nineteen"};
String[] high = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
public String numberToWords(int num) {
if(num == 0){
return "Zero";
}
//三位数三位数划分
int part1 = num % 1000;
num = num / 1000;
int part2 = num % 1000;
num = num / 1000;
int part3 = num % 1000;
num = num / 1000;
int part4 = num;
//StringBuilder提高效率,注意空格的填充
StringBuilder ans = new StringBuilder();
if(part4 != 0){//百万
ans.append(builderNumber(part4)).append(" ").append("Billion");
}
if(part3 != 0){//十万
ans.append(" ").append(builderNumber(part3)).append(" ").append("Million");
}
if(part2 != 0){//千
ans.append(" ").append(builderNumber(part2)).append(" ").append("Thousand");
}
if(part1 != 0){//千以下
ans.append(" ").append(builderNumber(part1));
}
return ans.toString().trim();//头尾去空
}
public String builderNumber(int num){
//千位以下的判断
int a = num % 10;
num = num / 10;
int b = num % 10;//十位
num = num / 10;
int c = num;//百位
StringBuilder ans = new StringBuilder();
if(c != 0){//百位不为0,添加百
ans.append(low[c]).append(" ").append("Hundred");
}
if(b == 1){//特殊情况,十几在中部寻找
ans.append(" ").append(mid[a]);
}else if(b == 0){//各位数字,在低部寻找
ans.append(" ").append(low[a]);
}else{//其他情况
ans.append(" ").append(high[b]).append(" ").append(low[a]);
}
return ans.toString().trim();
}
}
将非负整数 num 转换为其对应的英文表示输入:num = 123输出:"One Hundred Twenty Three"输入:num = 12345输出:"Twelve Thousand Three Hundred Forty Five"输入:num = 1234567输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"输入:num = 1234567891输出:"One Billion T