[leetcode] 273. Integer to English Words @ python

原题

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

Example 1:

Input: 123
Output: “One Hundred Twenty Three”
Example 2:

Input: 12345
Output: “Twelve Thousand Three Hundred Forty Five”
Example 3:

Input: 1234567
Output: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”
Example 4:

Input: 1234567891
Output: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”

解法

参考: https://leetcode.com/problems/integer-to-english-words/discuss/70688/Python-Clean-Solution
将所有可能的单词分组成为3个列表, 然后从尾部开始每三位进行读取, 使用遍历和递归. 例如: 1234567891, 先读取891, 得到res是’Eight Hundred Ninety One ', 然后读取567, 得到’Five Hundred Sixty Seven Thousand ', 加上之前的res, 结果是’Five Hundred Sixty Seven Thousand Eight Hundred Ninety One ', , 依次类推.

代码

class Solution(object):
    def __init__(self):
        self.lessThan20 = ["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
        self.tens = ["","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"]
        self.thousands = ["","Thousand","Million","Billion"]
    
    def numberToWords(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0:
            return 'Zero'
        res = ''
        for i in range(len(self.thousands)):
            if num % 1000 != 0:
                res = self.helper(num % 1000) + self.thousands[i] + ' '+ res
            num = num//1000
        return res.strip()
            
    def helper(self, num):
        if num == 0:
            return ''
        if num < 20:
            return self.lessThan20[num] + ' '
        if num < 100:
            return self.tens[num//10] + ' '+ self.helper(num%10)
        else:
            return self.lessThan20[num//100] + ' Hundred ' + self.helper(num%100)
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值