273.|273. Integer to English Words

【273.|273. Integer to English Words】Hard
找的LC上比较满意的答案了,一开始建立一个 LESS_THAN_20和TENS的String array来装常量。然后分为num < 20, num < 100, num < 1000, num < 1000000, num < 100000000来分类。注意一下 +” Hundred "这些都需要前后留一个空格. 还有为什么两个array里要放一个""元素。是为了index可以配合数据,比如TENS[1]是Ten, TENS[2] = Twenty. 注意下billion是十亿不是一亿哦。

class Solution { private final String[] LESS_THAN_20 = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven", "Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; private final String[] TENS = {"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; public String numberToWords(int num) { if (num == 0){ return "Zero"; } return helper(num); }private String helper(int num){ String res = ""; if (num < 20){ res = LESS_THAN_20[num]; } else if (num < 100){ res = TENS[num / 10] + " " + helper(num % 10); } else if (num < 1000){ res = helper(num / 100) + " Hundred " + helper(num % 100); } else if (num < 1000000){ res = helper(num / 1000) + " Thousand " + helper(num % 1000); } else if (num < 1000000000){ res = helper(num / 1000000) + " Million " + helper(num % 1000000); } else { res = helper(num / 1000000000) + " Billion " + helper(num % 1000000000); } return res.trim(); } }

    推荐阅读