Leetcode #273: Integer to English Words
In this guide, we solve Leetcode #273 Integer to English Words in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Recursion, Math, String
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
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
The time complexity is O(n) or O(1). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.