leetcode 273. Integer to English Words

来源:互联网 发布:建筑学软件 编辑:程序博客网 时间:2024/05/29 12:34

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"

class Solution(object):
    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 numberToWords(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0:
            return 'Zero'
        res = []
        if num < 0:
            res.append('Negative')
            num = abs(num)
        temp = num / 1000000000
        num = num % 1000000000
        if temp != 0:
            res.append(self.dic[temp])
            res.append('Billion')
        temp = num / 1000000
        num = num % 1000000
        if temp != 0:
            self.getHundred(temp, res)
            res.append('Million')
        temp = num / 1000
        num = num % 1000
        if temp != 0:
            self.getHundred(temp, res)
            res.append('Thousand')
        if num != 0:
            self.getHundred(num, res)
        return ' '.join(res)
        
    def getHundred(self, num, res):
        if num / 100 != 0:
            res.append(self.dic[num / 100])
            res.append('Hundred')
        num = num % 100
        if num != 0:
            if num in self.dic:
                res.append(self.dic[num])
            else:
                res.append(self.dic[num / 10 * 10])
                res.append(self.dic[num % 10])
            return res

0 0
原创粉丝点击