Giả sử chúng ta có một số bất kỳ từ 0 đến 2^31 - 1. Chúng ta phải chuyển đổi số đó thành chữ. Ví dụ: 512 sẽ thành "Five hundred twelve".
Các bước giải quyết:
- Định nghĩa các mảng: less_than_20 (1-19), tens (20,30...90), thousands (thousand, million, billion)
- Hàm helper(n): chuyển đổi số < 1000 thành chữ
- Phương thức chính: chia số thành các nhóm 3 chữ số, dùng helper và thêm đơn vị thousand/million/billion
Ví dụ
class Solution(object):
less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["","Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
thousands = ["", "Thousand", "Million", "Billion"]
def numberToWords(self, num):
if num == 0:
return "Zero"
ans = ""
i = 0
while num > 0:
if num % 1000 != 0:
ans = self.helper(num % 1000) + Solution.thousands[i] + " " + ans
i += 1
num //= 1000
return ans.strip()
def helper(self, n):
if n == 0:
return ""
elif n < 20:
return Solution.less_than_20[n] + " "
elif n < 100:
return Solution.tens[n//10] + " " + self.helper(n % 10)
else:
return Solution.less_than_20[n // 100] + " Hundred " + self.helper(n % 100)
ob = Solution()
print(ob.numberToWords(512))
print(ob.numberToWords(7835271))
Đầu vào
512 7835271
Đầu ra
Five Hundred Twelve Seven Million Eight Hundred Thirty Five Thousand Two Hundred Seventy One