美文网首页
Leetcode-273题:Integer to English

Leetcode-273题:Integer to English

作者: 八刀一闪 | 来源:发表于2016-10-08 22:18 被阅读147次

题目

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):

    def change3(self, num, num_str):
        if num in num_str:
            return num_str[num]
        result = []
        if num > 99:
            result.append(num_str[num/100])
            result.append('Hundred')
            num %= 100
        if num > 9:
            if num in num_str:
                result.append(num_str[num])
                num = 0
            else:
                result.append(num_str[num-num%10])
                num %= 10
        if num !=0:
            result.append(num_str[num])
        return ' '.join(result)

    def numberToWords(self, num):
        """
        :type num: int
        :rtype: str
        """
        num_str = {0:'Zero', 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', 1000:'Thousand', 1000000:'Million', 1000000000:'Billion'}
        if num == 0:
            return 'Zero'
        result = []
        t = 1000000000
        while t!=1 and num!=0:
            if num / t != 0:
                result.append(self.change3(num/t, num_str))
                result.append(num_str[t])
                num %= t
            t /= 1000
        #print num,t
        if num != 0:
            result.append(self.change3(num, num_str))
        return ' '.join(result)

相关文章

网友评论

      本文标题:Leetcode-273题:Integer to English

      本文链接:https://www.haomeiwen.com/subject/ojcpyttx.html