273. Integer to English Words

解法

难倒是不难,考验细心
坑:

  1. 单词不要拼错
  2. 10~19的注意挑出来
  3. 0的处理
class Solution(object):
    def numberToWords(self, num):
        """
        :type num: int
        :rtype: str
        """
        BILLION = 1000000000
        THOUSAND = 1000
        MILLION = 1000000

        if num==0:
            return "Zero"

        dic = {
            1: 'One',2: 'Two',3: 'Three',4: 'Four',5: 'Five',6: 'Six',7: 'Seven',8: 'Eight',9: 'Nine',10: 'Ten',
            11: 'Eleven',12: 'Twelve',13: 'Thirteen',14: 'Fourteen',15: 'Fifteen',16: 'Sixteen',17: 'Seventeen',
            18: 'Eighteen',19: 'Nineteen',
            20: 'Twenty',30: 'Thirty',40: 'Forty',50: 'Fifty',60: 'Sixty',70: 'Seventy',80: 'Eighty',90: 'Ninety'
        }

        def each_thousand(num):
            if num == 0:
                return ""
            hundred = num / 100
            ten = num % 100 - num % 10
            single = num % 10
            hundred = "" if hundred == 0 else "%s Hundred " % dic[hundred]
            if ten==10:
                ten = "%s "% dic[ten+single]
                single = ""
            else:
                ten = "%s " % dic[ten] if ten!=0 else ""
                single = "" if single == 0 else "%s " % dic[single]
            return hundred + ten + single

        def each_million(num):
            if num == 0:
                return ""
            thousand = each_thousand(num / THOUSAND)
            rest = each_thousand(num % THOUSAND)
            return ("%sThousand " % thousand if thousand!="" else "")+rest

        def each_billion(num):
            if num == 0:
                return ""
            rest = each_million(num % MILLION)
            thousands = each_thousand(num/ MILLION)
            return ("%sMillion " % thousands if thousands != "" else "") + rest

        billions = []
        while num:
            billions.append(num%BILLION)
            num /= BILLION
        billions = billions[::-1]
        res = ""
        for i in billions[:-1]:
            string = each_billion(i)
            if string != "":
                string += 'Billion '
            res += string
        res += each_billion(billions[-1])
        return res.strip()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值