一道比較難coding的題目。首先了解一下十進制數對應的數字具體讀法。一般是3位一逗號,代表着不同的數量級別,比如1234567讀作
One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
.後三位是567,即five hundred sixty seven,這個三位數在最終的表示中也是這樣的一個形式。234代表tow hundred thirty four。在最終表示過程中也是這樣的形式。不同的是,後面加了一個thousand,代表對應的數量級。所以需要加入數量級的東西。1即代表001三位中,1,直接用one表示即可。綜上我們可以以3位一間隔的形式將整個數字拆分開來。
需要注意的點如下:不妨設需要讀的數爲num。
num<20時,需要單獨的列出來
num%10==0時,同樣可以直接表示出來。
其餘的num爲3位數的情況時,需要按照數字位來運算。
具體代碼如下形式
class Solution {
int hundred=100;
int thousand=1000;
int million=1000000;
int billion=1000000000;
HashMap<Integer,String>map=new HashMap<>();
public String numberToWords(int num){
String[]num20={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven",
"Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
String[]num10={"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
map.put(hundred,"Hundred");
map.put(thousand,"Thousand");
map.put(million,"Million");
map.put(billion,"Billion");
for (int i=0;i<20;i++){
map.put(i,num20[i]);
}
for (int i=20,j=0;i<100;i+=10,j++){
map.put(i,num10[j]);
}
String res="";
for (int k=1000000000;k>=100;k/=1000){
if (num>=k){
res+=" "+get3(num/k)+" "+map.get(k);
num=num%k;
}
}
if(num!=0){
res+=" "+get3(num);
}
if (res.isEmpty()){
res+=" "+map.get(0);
}
return res.substring(1);
}
public String get3(int num){
String res="";
if (num>=hundred){
res+=" "+map.get(num/hundred)+" "+map.get(hundred);
num%=hundred;
}
if (num!=0){
if (num<20){
res+=" "+map.get(num);
}else if (num%10==0){
res+=" "+map.get(num);
}else{
res+=" "+map.get(num/10*10)+" "+map.get(num%10);
}
}
return res.substring(1);//每次res第一個字符都是空格,所以需要將開始的那個空格去掉
}
}
裏面有很多小細節。比如每次res拼接字符串之前需要添加“ ”,最後輸出時,控制最初的空格,所以使用子串的形式獲取字符串。同時。需要判斷num是否爲0控制邊界條件。