将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。
示例 1:
输入: 123 输出: "One Hundred Twenty Three"
示例 2:
输入: 12345 输出: "Twelve Thousand Three Hundred Forty Five"
示例 3:
输入: 1234567 输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:
输入: 1234567891 输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
按照英文习惯将数字从低位到高位每三位划分,然后从高位到低位读数,单位分别为Billion Million Thousand;
另外注意一下10-19的读法即可
class Solution:
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if (num == 0):
return "Zero"
result = "";
if (num > 999999999):
result += self.numberToWordsWithThreeDIgit(num // 1000000000) + " Billion"
num %= 1000000000
if (num > 999999):
result += self.numberToWordsWithThreeDIgit(num // 1000000) + " Million"
num %= 1000000
if (num > 999):
result += self.numberToWordsWithThreeDIgit(num // 1000) + " Thousand"
num %= 1000
if (num > 0):
result += self.numberToWordsWithThreeDIgit(num)
return result
def numberToWordsWithThreeDIgit(self, num):
num1 = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
num2 = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"]
tens = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
result = ""
if (num > 99):
result += " " + num1[num // 100 - 1] + " Hundred"
num %= 100
if (num > 19):
result += " " + tens[num // 10 - 2]
num %= 10
if (num > 9):
result += " " + num2[num - 10]
num = 0
if (num > 0):
result += " " + num1[num - 1]
return result
try1=Solution()
print(try1.numberToWords(5456467))