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 "" } } }
标签:
mathematical
, leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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 序列化与反序列化