【HARD】Integer to English Words

发布于: 2018-12-06 23:56
阅读: 9
评论: 0
喜欢: 0

问题

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" Hint:

Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)

分析过程

  • 输入:整形
  • 输出:这个整形的英语单词描述
  • 思路:
    • 将整形拆成几个三位数,以三位数为单位进行翻译。最高支持的 Billion,所以设计三次拆分,单位以此是 Billion, Million, Thousand。剩下的问题就是如何翻译三位数了。
    • 判断三位数有无百位,直接除以 100,有的话后面加 Hundred。
    • 剩下的两位数如果是 0 就直接什么都不干了,以几百直接结尾就行了。
    • 建立 0 ~ 20 的表,剩下的两位如果不是 0 且小于 20 的直接查表。
    • 如果剩下的两位大于 20,建立十位表,查出十位,拼上。
    • 继续考虑个位,如果个位是 0 就什么也不干,不是 0 就用 0 ~ 20 的表查出个位拼上。

解决方法

func convertHundred(_ i: Int) -> String {
    let v1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
    let v2 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
    
    let h = i / 100
    let t = i % 100
    let g = i % 10
    
    var result = ""
    
    result += h > 0 ? v1[h] + " Handred ": ""
    result += t < 20 ? (t == 0 ? "" : v1[t] + " ") : (v2[t / 10] + " " + v1[g] + " ")
    
    return result
}

func integer2English(_ i: Int) -> String {
    if i == 0 {
        return "Zero"
    }
    let v3 = ["Thousand", "Million", "Billion"]
    var val = i
    var result = convertHundred(val % 1000)
    for v in v3 {
        val /= 1000;
        result = val % 1000 > 0 ? convertHundred(val % 1000) + v + " " + result : result;
    }
    

    return result
}

print(integer2English(100100456789))

Thanks for reading.

All the best wishes for you! 💕