[一起来刷leetcode吧][26]--No.273 Integer to English Words

这篇文章是程序自动发表的,详情可以见 这里
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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值