HardNo. 0273
Integer to English Words — LeetCode 273 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Recursion, Math, String
- Reading time
- 10 min
- Source
- leetcode.com
The problem
Convert a non-negative integer num to its English words representation.
Example
- Input
- num = 123
- Output
- "One Hundred Twenty Three"
Python solution
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'
lt20 = [
'',
'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',
]
thousands = ['Billion', 'Million', 'Thousand', '']
def transfer(num):
if num == 0:
return ''
if num < 20:
return lt20[num] + ' '
if num < 100:
return tens[num // 10] + ' ' + transfer(num % 10)
return lt20[num // 100] + ' Hundred ' + transfer(num % 100)
res = []
i, j = 1000000000, 0
while i > 0:
if num // i != 0:
res.append(transfer(num // i))
res.append(thousands[j])
res.append(' ')
num %= i
j += 1
i //= 1000
return ''.join(res).strip()Complexity
- Time
- O(n) or O(1)
- Space · auxiliary
- O(1)
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 273. Integer to English Words is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0002 | Add Two Numbers | Medium |
| 0043 | Multiply Strings | Medium |
| 0050 | Pow(x, n) | Medium |
| 0060 | Permutation Sequence | Hard |
| 0168 | Excel Sheet Column Title | Easy |
| 0171 | Excel Sheet Column Number | Easy |
Frequently asked questions
- How hard is LeetCode 273. Integer to English Words?
LeetCode 273. Integer to English Words is rated Hard on LeetCode.
- What topics does LeetCode 273. Integer to English Words cover?
LeetCode 273. Integer to English Words is tagged Recursion, Math and String on LeetCode.