[Python] Naive But Clear Method


  • -1
    M
    class Solution(object):
    def __init__(self):
        self.small_dict = {
            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:'Fifthteen',16:'Sixteen',17:'Seventeen',18:'Eighteen',19:'Nineteen',
            20:'Twenty',30:'Thirty',40:'Fourty',50:'Fifty',60:'Sixty',70:'Seventy',80:'Eighty',90:'Ninety',100:'Hundred',
        }
    
        self.big_dict = {
            1:'',
            1000:'Thousand',
            1000000:'Million',
            1000000000:'Billion',
        }
    
    def numberToWords(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0:
            print 'Zero'
            return 'Zero'
       
        left = num
        res = ""
        for divider in sorted(self.big_dict.keys(),reverse=True):
            quotient = left / divider
            left = left % divider
            tmp_str = self.smallNumberToWords(quotient)
            if tmp_str != "":
                res += "%s %s " % (tmp_str,self.big_dict[divider])
        print res.strip()
    
    def smallNumberToWords(self, num):
        if num == 0 : return ""
        res = ""
        hundred = num / 100
        single = num % 10
        tens = num % 100 - single
        if tens == 10:
            single += 10
        if hundred != 0:
            res += "%s Hundred "%self.small_dict[hundred]
        if tens > 10:
            res += "%s "%self.small_dict[tens]
        if single != 0:
            res += "%s"%self.small_dict[single]
        return res.strip()

  • 0
    M

    Run Time 72ms


  • 0
    Y

    How did you pass with 'Fourty' and 'Fifthteen'?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.