解题思路:由于最大输入值不可能大于231- 1.即2147483647,第十位:Billion;第七位:Million;第四位:Thousand;第一位:个位。由此可能观察到,将输入值分成四个小组,每三个一组,从低到高依次输入四个小组中。然分别对每个小组中处理,分别百位,十位,个位。
Java实现:
public class Solution {
public String numberToWords(int num) {
if(num==0) return "Zero";
int[] grp=new int[4];
String[] strNum=new String[4];
strNum[0]="";
strNum[1]="";
strNum[2]="";
strNum[3]="";
int i=0;
while(num!=0){
int mod=num%1000;
grp[i++]=mod;
num=num/1000;
}
for(int j=i;j<grp.length;j++)
grp[j]=0;
for(int k=0;k<grp.length;k++){
int third=grp[k]/100;
if(third!=0){
switch(third){
case 1:strNum[k]+="One ";break;
case 2:strNum[k]+="Two ";break;
case 3:strNum[k]+="Three ";break;
case 4:strNum[k]+="Four ";break;
case 5:strNum[k]+="Five ";break;
case 6:strNum[k]+="Six ";break;
case 7:strNum[k]+="Seven ";break;
case 8:strNum[k]+="Eight ";break;
case 9:strNum[k]+="Nine ";break;
}
strNum[k]+="Hundred ";
}
grp[k]=grp[k]%100;
int second=grp[k]/10;
if(second!=0){
switch(second){
case 1:
switch(grp[k]){
case 10:strNum[k]+="Ten ";break;
case 11:strNum[k]+="Eleven ";break;
case 12:strNum[k]+="Twelve ";break;
case 13:strNum[k]+="Thirteen ";break;
case 14:strNum[k]+="Fourteen ";break;
case 15:strNum[k]+="Fifteen ";break;
case 16:strNum[k]+="Sixteen ";break;
case 17:strNum[k]+="Seventeen ";break;
case 18:strNum[k]+="Eighteen ";break;
case 19:strNum[k]+="Nineteen ";break;
}
break;
case 2:strNum[k]+="Twenty ";break;
case 3:strNum[k]+="Thirty ";break;
case 4:strNum[k]+="Forty ";break;
case 5:strNum[k]+="Fifty ";break;
case 6:strNum[k]+="Sixty ";break;
case 7:strNum[k]+="Seventy ";break;
case 8:strNum[k]+="Eighty ";break;
case 9:strNum[k]+="Ninety ";break;
}
}
if(second!=1){
grp[k]=grp[k]%10;
int first=grp[k];
if(first!=0){
switch(first){
case 1:strNum[k]+="One ";break;
case 2:strNum[k]+="Two ";break;
case 3:strNum[k]+="Three ";break;
case 4:strNum[k]+="Four ";break;
case 5:strNum[k]+="Five ";break;
case 6:strNum[k]+="Six ";break;
case 7:strNum[k]+="Seven ";break;
case 8:strNum[k]+="Eight ";break;
case 9:strNum[k]+="Nine ";break;
}
}
}
if(strNum[k].length()>0){
switch(k){
case 1:strNum[k]+="Thousand ";break;
case 2:strNum[k]+="Million ";break;
case 3:strNum[k]+="Billion ";break;
}
}
}
String res=strNum[3]+strNum[2]+strNum[1]+strNum[0];
return res.substring(0,res.length()-1);
}
}
题目地址:
https://leetcode.com/problems/integer-to-english-words/
版权声明:本文为博主原创文章,未经博主允许不得转载。