package LeetCode_273
/**
* 273. Integer to English Words
* https://leetcode.com/problems/integer-to-english-words/
* Convert a non-negative integer num to its English words representation.
Example 1:
Input: num = 123
Output: "One Hundred Twenty Three"
Example 2:
Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: num = 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
Constraints:
0 <= num <= 2^31 - 1
* */
class Solution {
/*
* solution: recursion to combine result string by numbers <20,20,100,1000,1000000,1000000000,
* Time:O(n), Space:O(n)
* */
//0-19
private val arrayUnder20 = arrayOf(
"Zero", "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"
)
//0,10-90
private val arrayUp = arrayOf(
"Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
)
fun numberToWords(num: Int): String {
if (num == 0) {
return "Zero"
}
val result = combine(num)
return result.substring(1, result.length)
}
private fun combine(num: Int): String {
if (num >= Math.pow(10.0, 9.0)) {
return combine(num / Math.pow(10.0, 9.0).toInt()) + " Billion" + combine(num % Math.pow(10.0, 9.0).toInt())
} else if (num >= Math.pow(10.0, 6.0)) {
return combine(num / Math.pow(10.0, 6.0).toInt()) + " Million" + combine(num % Math.pow(10.0, 6.0).toInt())
} else if (num >= 1000) {
//handle numbers in Thousand and other places numbers
return combine(num / 1000) + " Thousand" + combine(num % 1000)
} else if (num >= 100) {
//handle numbers in Hundred and other places numbers
return combine(num / 100) + " Hundred" + combine(num % 100)
} else if (num >= 20) {
//handle tens and ones digits
return " " + arrayUp[num / 10] + combine(num % 10)
} else if (num >= 1) {
return " " + arrayUnder20[num]
} else {
return ""
}
}
}