動機
天啊
Problem
Convert a non-negative integer num
to its English words representation.
Example 1:
Input: num = 123Output: One Hundred Twenty Three
Example 2:
Input: num = 12345Output: Twelve Thousand Three Hundred Forty Five
Example 3:
Input: num = 1234567Output: One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
Example 4:
Input: num = 1234567891Output: One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One
Constraints:
0 <= num <= 231 - 1
Sol
先把3位數的function先做出來,之後就是慢慢往上推
class Solution:
def numberToWords(self, num: int) -> str:
v1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
v2 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
v3 = ["Thousand", "Million", "Billion"]
ret = []
def hund(n):
a,b,c = n//100, n%100, n%10
if b < 20:
ret = v1[b]
elif c > 0:
ret = f'{v2[b//10]} {v1[c]}'
else:
ret = f'{v2[b//10]}'
if a > 0:
if b > 0:
ret = f'{v1[a]} Hundred {ret}'
else:
ret = f'{v1[a]} Hundred'
return ret
ret = hund(num%1000)
for i in range(3):
num = num//1000
if num % 1000 > 0:
ret = f'{hund(num%1000)} {v3[i]} {ret}'
if ret:
if ret[-1] == " ":
return ret[:-1]
else:
return ret
else:
return "Zero"