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 - 1When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Converting numbers into English words using a brute force strategy involves breaking the number down into every possible combination of smaller pieces and manually looking up the word for each piece. You would exhaustively list and check every conceivable way to translate the parts of the number, piece by piece, until you have covered the entire value.
Here's how the algorithm would work step-by-step:
class Solution:
def numberToWords(self, number_value: int) -> str:
if number_value == 0:
return "Zero"
# We map base words to exhaustively cover all individual translation chunks
digit_translations = {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: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen", 20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", 70: "Seventy", 80: "Eighty", 90: "Ninety"}
scale_translations = {100: "Hundred", 1000: "Thousand", 1000000: "Million", 1000000000: "Billion"}
string_representation = str(number_value)
# Slicing the number into groupings helps process thousands and millions correctly
def generate_chunk_words(current_subnumber):
if current_subnumber == 0:
return ""
elif current_subnumber < 20:
return digit_translations[current_subnumber]
elif current_subnumber < 100:
tens_digit = (current_subnumber // 10) * 10
remainder_digit = current_subnumber % 10
if remainder_digit == 0:
return digit_translations[tens_digit]
return digit_translations[tens_digit] + " " + digit_translations[remainder_digit]
else:
hundreds_digit = current_subnumber // 100
remainder_value = current_subnumber % 100
hundred_word = digit_translations[hundreds_digit] + " Hundred"
if remainder_value == 0:
return hundred_word
return hundred_word + " " + generate_chunk_words(remainder_value)
accumulated_words = []
scales = [1000000000, 1000000, 1000, 1]
scale_names = ["Billion", "Million", "Thousand", ""]
# Iterating through scales ensures each magnitude is processed in correct order
for index_counter in range(len(scales)):
current_scale = scales[index_counter]
if number_value >= current_scale:
chunk_value = number_value // current_scale
number_value %= current_scale
translated_chunk = generate_chunk_words(chunk_value)
accumulated_words.append(translated_chunk)
if scale_names[index_counter]:
accumulated_words.append(scale_names[index_counter])
final_translation_result = " ".join([word for word in accumulated_words if word])
# Stitching the translated pieces together forms the final complete sentence
return final_translation_resultThe optimal strategy mirrors how humans naturally read and speak large numbers by breaking them down into digestible chunks of thousands. Instead of translating the whole number at once, we chop it up from right to left and label each chunk with its proper scale word like thousand, million, or billion.
Here's how the algorithm would work step-by-step:
class Solution:
def numberToWords(self, input_number: int) -> str:
# Zero requires a direct check because it does not follow scale naming rules.
if input_number == 0:
return "Zero"
below_twenty_words = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens_multiple_words = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
scale_name_words = ["", "Thousand", "Million", "Billion"]
def convert_three_digits(triplet_number: int) -> str:
triplet_phrase = ""
if triplet_number >= 100:
triplet_phrase += below_twenty_words[triplet_number // 100] + " Hundred "
triplet_number %= 100
if triplet_number >= 20:
triplet_phrase += tens_multiple_words[triplet_number // 10] + " "
triplet_number %= 10
if triplet_number > 0:
triplet_phrase += below_twenty_words[triplet_number] + " "
return triplet_phrase.strip()
accumulated_words = ""
scale_index = 0
# Processing groups of three digits from right to left maps directly to how humans read numbers.
while input_number > 0:
current_triplet = input_number % 1000
if current_triplet > 0:
translated_triplet = convert_three_digits(current_triplet)
scale_suffix = scale_name_words[scale_index]
current_chunk = translated_triplet + (" " + scale_suffix if scale_suffix else "")
accumulated_words = current_chunk + (" " + accumulated_words if accumulated_words else "")
input_number //= 1000
scale_index += 1
# Final cleanup ensures standard spacing regardless of trailing or leading spaces in chunks.
return accumulated_words.strip()| Case | How to Handle |
|---|---|
| Input is exactly zero | Return the explicit string Zero since the standard chunk processing loop would otherwise produce an empty result. |
| Maximum 32-bit signed integer boundary values | Use a 64-bit integer type or standard language handling to prevent overflow when processing billions. |
| Numbers with internal zeros such as 1000015 | Skip empty thousand chunks cleanly without inserting extra spaces or redundant scale words. |
| Teens and numbers ending in zero like 10, 11, or 20 | Use specialized lookup arrays for numbers from 10 to 19 and tens multipliers to bypass standard teens logic. |
| Exact multiples of thousands, millions, and billions | Append scale words only when the corresponding thousand block value is strictly greater than zero. |
| Negative numbers | Assume valid non-negative inputs per the problem constraints or prepend a Negative word if extended. |
| Single digit numbers from 1 to 9 | Map directly to the base units array without invoking any recursive chunking logic. |
| Numbers with trailing spaces between concatenated chunks | Accumulate words into a list and join them with a single space to avoid duplicate whitespace. |