这篇文章是程序自动发表的,详情可以见
这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是leetcode的第273题--Integer to English Words
题目
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"
思路 用递归。难点在于十几的数的表示,12不能是ten two。以及要处理好零:比如10000,如果不加判断,直接会得到ten zero thousand zero zero zero。同样的,由于字符串是不可变的,所有、以在过程都使用列表,最后再join。再如100000不能是one milion thousand
show me the code
class Solution(object): def numberToWords(self, num): """ :type num: int :rtype: str """ s1 = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] s12 = ['Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'] s2 = ['Zero','Ten','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'] s3 = ['','Thousand','Million','Billion'] if num == 0: return 'Zero' num = list(str(num))[::-1] ans = [] def parse(s,count,ans): if s == []: return n = int(s[0]) del s[0] parse(s,count 1,ans) if count%3 == 2 and n is not 0: ans.append(s2[n]) else : if n == 0: if count in [4,7,11] and ans[-1] not in s3: ans.append(s3[(count-1)/3]) return ans.append(s1[n]) if count % 3 == 0: ans.append('Hundred') elif count%3 == 1: if n is not 0 and len(ans)>1 and ans[-2] =='Ten': del ans[-1] ans[-1] = s12[n] if count > 1:ans.append(s3[(count-1)/3]) parse(num,1,ans) return ' '.join(ans)