Lintcode 1305. Integer to English Words (Easy) (Python)

1305. Integer to English Words

Description:

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1.

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”

Code:

class Solution:
    """
    @param num: a non-negative integer
    @return: english words representation
    """
    def numberToWords(self, num):
        # Write your code here
        if num == 0:
            return "Zero"
        word1000 = ["", " Thousand", " Million", " Billion", " Trillion"]
        st = '%d'%num
        ls = len(st)
        unit = math.floor((ls-1)/3)
        res = ""
        if ls%3 == 2:
            res = self.eng(int(st[:2])) + word1000[unit]
            st = st[2:]
        elif ls%3 == 1:
            res = self.eng(int(st[0])) + word1000[unit]
            st = st[1:]
        elif ls%3 == 0:
            res = self.eng(int(st[:3])) + word1000[unit]
            st = st[3:]
        unit -= 1

        while unit >=  0:
            tmp = st[:3]
            res = res + " " + self.eng(int(tmp[:])) + word1000[unit]
            st = st[3:]
            unit -= 1
        return res




    def eng(self, num):
        word1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
        word10 = ["Ten", "Eleven", "Twelve", "Thirteen", "Forteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
        word20 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]

        st = '%d'%num
        if len(st) == 1:
            return word1[num]
        if len(st) == 2 and num<20:
            return word10[int(st[1])]
        if len(st) == 2 and num>=20:
            if num%10 == 0:
                return word20[int(st[0])]
            elif num%10 != 0:
                return word20[int(st[0])] + " " + self.eng(int(st[1]))
        if len(st) == 3:
            return word1[int(st[0])] + " Hundred " + self.eng(int(st[1:]))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值