码迷,mamicode.com
首页 > 其他好文 > 详细

Integer to English Words 解答

时间:2015-11-09 01:31:20      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:

Question

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:

  1. Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
  2. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
  3. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)

Solution

根据英文表示数字的规则,这题的关键在于三位三位的处理数字。

小于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         

 

Integer to English Words 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4948761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!