leetcode刷题笔记 273题 整数转换英文表示

leetcode刷题笔记 273题 整数转换英文表示

源地址:273. 整数转换英文表示

问题描述:

将非负整数 num 转换为其对应的英文表示。

示例 1:

输入:num = 123
输出:"One Hundred Twenty Three"
示例 2:

输入:num = 12345
输出:"Twelve Thousand Three Hundred Forty Five"
示例 3:

输入:num = 1234567
输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:

输入:num = 1234567891
输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

提示:

0 <= num <= 231 - 1

//按英文数字处理逻辑 构建函数三位一处理
object Solution {
    def numberToWords(num: Int): String = {
        val num0_19 = Array[String]("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
        
        val num20_90 = Array[String]("Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
        
        val num1000 = Array[String]("Billion ", "Million ", "Thousand ", "")
        
        var ans = ""
        var numX = num
        
        def get(x: Int): String = {
            var res = ""
            var curX = x
            if (curX >= 100) {
                res += num0_19(curX/100) + " Hundred "
                curX = curX % 100
            }
            if (curX >= 20) {
                res += num20_90(curX/10 - 2) + " "
                curX = curX % 10
                if (curX != 0) res += num0_19(curX) + ' '
            }
            else {
                if (curX != 0) res += num0_19(curX) + ' '
            }
            return res
        }
        
        if (numX == 0) return "Zero"
        var i = 1e9
        var j = 0
        
        while (i >= 1) {
            if (numX >= i) {
                ans += get((numX/i).toInt) + num1000(j)
                numX = (numX % i).toInt
            }
            i /= 1000
            j += 1
        }
        
        return ans.dropRight(1)
    }
}
posted @ 2020-11-09 22:40  ganshuoos  阅读(187)  评论(0编辑  收藏  举报