Problem: https://leetcode.com/problems/integer-to-english-words/
Solution:
重点在于如何把长数分割成小的部分考虑(分别为billion,million,thousand,各部分均有三位数字)
class Solution {
public String single(int num) {
switch(num) {
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";
}
return "";
}
public String twoDigits(int num) {
switch(num) {
case 10: return "Ten";
case 11: return "Eleven";
case 12: return "Twelve";
case 13: return "Thirteen";
case 14: return "Fourteen";
case 15: return "Fifteen";
case 16: return "Sixteen";
case 17: return "Seventeen";
case 18: return "Eighteen";
case 19: return "Nineteen";
}
return "";
}
public String decimal(int num) {
switch(num) {
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";
}
return "";
}
public String twoString(int num) {
if (num < 10) {
return single(num);
} else if (num < 20) {
return twoDigits(num);
} else {
int tenner = num/10;
int res = num%10;
if (res == 0) {
return decimal(tenner);
} else {
return decimal(tenner) + " " + single(res);
}
}
}
public String three(int num) {
int hundred = num/100;
int res = num%100;
if (hundred == 0) {
return twoString(num);
} else {
if (res == 0) {
return single(hundred) + " Hundred";
} else {
return single(hundred) + " Hundred " + twoString(res);
}
}
}
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
int billion = num/1000000000;
int million = (num-billion*1000000000)/1000000;
int thousand = (num-billion*1000000000-million*1000000)/1000;
int res = num-billion*1000000000-million*1000000-thousand*1000;
String s = "";
if (billion != 0) {
s += three(billion) + " Billion";
}
if (million != 0) {
if(!s.isEmpty()) {
s += " ";
}
s += three(million) + " Million";
}
if (thousand != 0) {
if(!s.isEmpty()) {
s += " ";
}
s += three(thousand) + " Thousand";
}
if (res != 0) {
if(!s.isEmpty()) {
s += " ";
}
s += three(res);
}
return s;
}
}