fun numberToWords(num: Int): String? { var num = num if (num == 0) { return LESS_THAN_TWENTY.get(0) } var i = 0 val res = StringBuilder() while (num > 0) { if (num % 1000 != 0) { res.insert(0, " ") res.insert(0, THOUSANDS.get(i)) res.insert(0, helper(num % 1000)) } num /= 1000 i++ } return res.toString().trim { it <= ' ' } }
Math , String . Try to find the pattern first . The numbers less than 1000 , e.g . xyz , can be x Hundred y '' ty '' z . The numbers larger than 1000 , we need to add thousand or million or billion . Given a number num , we pronounce the least significant digits first . Then concat the result to the end to next three least significant digits . So the recurrence relation is : Next result of num = the pronunciation of least three digits + current result of num After that , remove those three digits from number . Stop when number is 0 .