[分析]
这题通过率之所以非常低是因为有很多corner case,代码写得不好时就很容易在各种corner case上刷跟头,第二十遍才被Accept,自己还真是有耐心。然后看到讨论区中的解答,一对比,差距啊,努力努力再努力!
注意:不需要添加“and”
大神漂亮的作品:
[url]https://leetcode.com/discuss/55462/my-clean-java-solution-very-easy-to-understand[/url]
这题通过率之所以非常低是因为有很多corner case,代码写得不好时就很容易在各种corner case上刷跟头,第二十遍才被Accept,自己还真是有耐心。然后看到讨论区中的解答,一对比,差距啊,努力努力再努力!
注意:不需要添加“and”
大神漂亮的作品:
[url]https://leetcode.com/discuss/55462/my-clean-java-solution-very-easy-to-understand[/url]
public class Solution {
public String numberToWords(int num) {
if (num == 0) return "Zero";
StringBuilder result = new StringBuilder();
boolean hasBillion = false;
boolean hasMillion = false;
boolean hasThousand = false;
if (num >= 1000000000) {
hasBillion = true;
result.append(digits[num / 1000000000]).append(' ').append("Billion").append(' ');
num %= 1000000000;
}
if (num >= 1000000) {
hasMillion = true;
result.append(readALessThousandNum(String.valueOf(num / 1000000), false)).append(' ').append("Million").append(' ');
num %= 1000000;
} /*else if (hasBillion && num > 0) {
result.append("and").append(' ');
}*/
if (num >= 1000) {
hasThousand = true;
result.append(readALessThousandNum(String.valueOf(num / 1000), false)).append(' ').append("Thousand").append(' ');
num %= 1000;
} /*else if (hasMillion && num > 0) {
result.append("and").append(' ');
}*/
result.append(readALessThousandNum(String.valueOf(num), hasThousand));
return result.toString().trim();
}
private String[] digits = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
private String[] tenx = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen","Eighteen", "Nineteen"
};
private String[] tens = {"","","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
public String readALessThousandNum(String num, boolean hasThousand) {
if (num.length() == 1)
num = "00" + num;
else if (num.length() == 2)
num = "0" + num;
StringBuilder result = new StringBuilder();
boolean hasHundred = false;
if (num.charAt(0) != '0') {
hasHundred = true;
result.append(digits[num.charAt(0) - '0']).append(' ').append("Hundred").append(' ');
} /*else if (hasThousand && (num.charAt(1) != '0'|| num.charAt(0) != '0')) {
result.append("and");
}*/
if (num.charAt(1) == '0' && num.charAt(2) != '0') {
// if ((hasHundred || hasThousand))
// result.append("and").append(' ');
result.append(digits[num.charAt(2) - '0']).append(' ');
} else if (num.charAt(1) == '1') {
// if (hasHundred || hasThousand)
// result.append("and").append(' ');
result.append(tenx[num.charAt(2) - '0']).append(' ');
} else {
result.append(tens[num.charAt(1) - '0']).append(' ');
if (num.charAt(2) != '0')
result.append(digits[num.charAt(2) - '0']).append(' ');
}
return result.toString().trim();
}
}