273 Integer to English Words

Convert a non-negative integer num to its English words representation.

Example 1:

Input: num = 123
Output: "One Hundred Twenty Three"

Example 2:

Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Constraints:

  • 0 <= num <= 231 - 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
    def numberToWords(self, num: int) -> str:
        if not num:
            return 'Zero'
        ones = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
                'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven',
                'Twelve', 'Thirteen', 'Fourteen', 'Fifteen',
                'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
        tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty',
                'Sixty', 'Seventy', 'Eighty', 'Ninety']
        thoudands = ['', 'Thousand', 'Million', 'Billion', 'Trillion']
        res = ''
        i = 0
        while num > 0:
            if num % 1000 > 0:
                res = ' ' + thoudands[i] + res
                current = ''
                third = num // 100 % 10
                second = num % 100
                first = num % 10
                if third:
                    current += (' ' + ones[third] + ' Hundred')
                if 0 < second < 20:
                    current += (' ' + ones[second])
                else:
                    if second:
                        current += (' ' + tens[second // 10])
                    if first:
                        current += (' ' + ones[first])
                res = current + res
            num //= 1000
            i += 1
        return res.strip()