Re: [閒聊] 每日leetcode

看板Marginalman作者 (JerryChung)時間1年前 (2024/08/08 07:08), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串664/1548 (看更多)
https://leetcode.com/problems/integer-to-english-words 273. Integer to English Words Python Code: class Solution: def numberToWords(self, num: int) -> str: if num == 0: return "Zero" def one(num): """Convert a number less than 20 to words.""" switcher = [ "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight" , "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ] return switcher[num - 1] if num > 0 else "" def ten(num): """Convert a number between 20 and 99 to words.""" switcher = [ "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", " Eighty", "Ninety" ] return switcher[num // 10 - 2] if num >= 20 else "" def two(num): """Convert a number less than 100 to words.""" if num < 20: return one(num) else: return ten(num) + ("" if num % 10 == 0 else " " + one(num % 10 )) def three(num): """Convert a number less than 1000 to words.""" if num == 0: return "" elif num < 100: return two(num) else: return one(num // 100) + " Hundred" + ("" if num % 100 == 0 else " " + two(num % 100)) def convert(num): """Convert a number to words.""" if num == 0: return "Zero" billion = num // 1000000000 million = (num // 1000000) % 1000 thousand = (num // 1000) % 1000 remainder = num % 1000 result = "" if billion > 0: result += three(billion) + " Billion" if million > 0: result += (" " if result else "") + three(million) + " Million " if thousand > 0: result += (" " if result else "") + three(thousand) + " Thousand" if remainder > 0: result += (" " if result else "") + three(remainder) return result.strip() return convert(num) 字太多懶得手打 一開始估狗 "數字 英文 全" 顯示的網站說分成4組 所以就 :( 懶得改了 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.61.169 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1723072110.A.493.html
文章代碼(AID): #1ci_vkIJ (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ci_vkIJ (Marginalman)