273. Integer to English Words

复制代码
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 ""
        }
    }
}
复制代码

 

posted @   johnny_zhao  阅读(80)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-01-20 42. Trapping Rain Water
2020-01-20 序列化与反序列化
点击右上角即可分享
微信分享提示