算法提高之LeetCode刷题

【算法】Integer to English Words 数字转

2020-02-06  本文已影响0人  无良剑染

题目

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"

一个小于 2^31 - 1 的非负整数,转换成英文单词

解题思路

  1. 从 0 ~ 19 都有单独的单词对应
  2. 从 20 ~ 99 均为 Twenty One,这种两个单词组成的数字,用 / 和 % 计算出十位和个位,然后将对应单词组合即可
  3. 从 100 开始就有了 Hundred,Thousand,Million,Billion 数字单位,可依据相应位数用 / 和 % 计算出数字单位前后的数,并递归找到对应单词,将数字单位插入中间即可
  4. 如 20,100,1000 等这类整数,拆分成两个数字时,第二个数字为零,此情况下第二个数字不用进行递归操作,直接在数字单位后添加空字符即可

代码实现

Runtime: 8 ms
Memory: 20.4 MB

let belowTen = ["Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"]
let teens = ["Ten", "Eleven", "Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
let belowHundreds = ["","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"]
class Solution {
    func numberToWords(_ num: Int) -> String {
        var result = ""
        var secNum = 0
        if(num < 10){
            //个位数
            result = belowTen[num]
        }else if (num < 20){
            //10 至 19
            result = teens[num % 10]
        }else if (num < 100){
            //20 至 99
            //判断类似于 Twenty One 这种两个单词表示的情况
            secNum = num % 10
            result = belowHundreds[num / 10] + ((secNum == 0) ? "" :" " + belowTen[secNum])
        } else if (num < 1000) {
            // 100 至 999
            // 从百位数拆分 并将百位数单位插入 并将十个位递归
            secNum = num % 100
            return belowTen[num / 100] + " Hundred" + ((secNum == 0) ? "" :" " + self.numberToWords(secNum))
        } else if (num < 1000000) {
            // 1001 至 999999
            // 从千位数拆分 并将千位数单位插入 并将拆开的两部分递归
            secNum = num % 1000
            return self.numberToWords(num / 1000) + " Thousand" + ((secNum == 0) ? "" :" " + self.numberToWords(secNum))
        } else if (num < 1000000000) {
            // 1000001 至 1000000000
            // 从百万位数拆分 并将百万位数单位插入 并将拆开的两部分递归
            secNum = num % 1000000
            return self.numberToWords(num / 1000000) + " Million" + ((secNum == 0) ? "" :" " + self.numberToWords(secNum))
        } else {
            // 大于 1000000001
            // 从十亿位数拆分 并将十亿位数单位插入 并将拆开的两部分递归
            secNum = num % 1000000000
            return self.numberToWords(num / 1000000000) + " Billion" + ((secNum == 0) ? "" :" " + self.numberToWords(secNum))
        }
        return result
    }
}

代码地址:https://github.com/sinianshou/EGSwiftLearning

上一篇下一篇

猜你喜欢

热点阅读