9/20/2020

[LeetCode] 273. Integer to English Words

Problem : https://leetcode.com/problems/integer-to-english-words/

Split the number into hundreds, then convert hundred into words.


class Solution:
    def numberToWords(self, num: int) -> str:
        ones = ['One', 'Two', 'Three', 'Four', \
                'Five', 'Six', 'Seven', 'Eight', \
                'Nine']
        
        odds = ['Eleven', 'Twelve',\
                    'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen',\
                    'Seventeen', 'Eighteen', 'Nineteen']
        
        tens = ['Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', \
                'Sixty', 'Seventy', 'Eighty', 'Ninety']
        
        
        def hundreds(n, output):           
            if n >= 100:
                output.append(ones[(n//100) - 1])
                output.append("Hundred")
                hundreds(n%100, output)
            elif n == 10 or n >= 20:
                output.append(tens[n // 10 -1])    
                hundreds(n%10, output)          
            elif 10 < n < 20:
                output.append(odds[n - 11])
            elif n > 0:
                output.append(ones[n-1])
        
        if num == 0:
            return "Zero"
        
        output = []
        
        while num > 0:
            if num < 1000:
                hundreds(num, output)
                break
            elif 1000 <= num < 1000 * 1000:
                hundreds(num // 1000, output)
                output.append('Thousand')
                num = num % 1000
            elif 1000 * 1000 <= num < 1000 * 1000 * 1000:
                hundreds(num // (1000 * 1000), output)
                output.append('Million')
                num = num % (1000 * 1000)
            else:
                hundreds(num // (1000 * 1000 * 1000), output)
                output.append('Billion')
                num = num % (1000 * 1000 * 1000)
        
        return ' '.join(output)    

No comments:

Post a Comment