【HARD】Integer to English Words

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

问题

原题链接:https://leetcode.com/problems/integer-to-english-words/

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

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

分析过程

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

解决方法

class Solution {
    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] + " Hundred ": ""
        result += t < 20 ? (t == 0 ? "" : (t == 0 ? "" : v1[t] + " ")) : (v2[t / 10] + " " + (g == 0 ? "" : v1[g] + " "))
        
        return result
    }
    func numberToWords(_ num: Int) -> String {
        if num == 0 {
            return "Zero"
        }
        let v3 = ["Thousand", "Million", "Billion"]
        var val = num
        var result = convertHundred(val % 1000)
        for v in v3 {
            val /= 1000;
            result = val % 1000 > 0 ? convertHundred(val % 1000) + v + " " + result : result;
        }
        
        return String(result.dropLast())
    }
}

Thanks for reading.

All the best wishes for you! 💕