标签:
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Hint:
根据英文表示数字的规则,这题的关键在于三位三位的处理数字。
小于100的数:1. 小于20的,没有什么规律,只能存到数组里 2. 大于等于20的,可以按十位和个位拆解。
如 23,345,100,089
先和billion(1,000,000,000)比较,除法得到23
再和million(1,000,000)比较,除法得到345,345再和hundred(100)比较,得到3和45
。。。
1 class Solution(object): 2 def numberToWords(self, num): 3 """ 4 :type num: int 5 :rtype: str 6 """ 7 if num == 0: 8 return "Zero" 9 less_then_twenty_words = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"] 10 ty_words = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"] 11 dex_words = ["Billion", "Million", "Thousand", "Hundred"] 12 radix = [1000000000, 1000000, 1000, 100] 13 s = "" 14 for i in range(len(radix)): 15 count = num / radix[i] 16 if count == 0: 17 continue 18 s = s + self.numberToWords(count) + " " + dex_words[i] + " " 19 num = num % radix[i] 20 if num < 20: 21 s = s + less_then_twenty_words[num] 22 elif num < 100: 23 s = s + ty_words[num / 10 - 2] + " " + less_then_twenty_words[num % 10] 24 return s.strip() 25
标签:
原文地址:http://www.cnblogs.com/ireneyanglan/p/4948761.html