NeetCode #942LC-273HardMath & Geometry
← Back to All Problems#942 · #273 · Integer to English Words(整数转换英文表示)
📌 Problem Statement & Constraints
Given a non-negative integer
num, return its English words representation following standard American grouping, so 123 becomes One Hundred Twenty Three. Constraints: 0 <= num <= 2^31 - 1.💡 Core Algorithmic Approaches
- Split the number into groups of three digits from the least significant side, labelled
Thousand,Million, andBillion. - Write a helper
three(x)that handles0..999: hundreds with the wordHundred, then the tens or teens table, then the ones digit. - For each group, if it is non-zero, append its words plus the group suffix; then reverse the collected groups.
- Special-case
num == 0to returnZero, because the main loop would otherwise produce nothing.
💻 Benchmark Python3 Implementation
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return "Zero"
ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"]
def three(x: int) -> str:
parts = []
if x >= 100:
parts.append(ones[x // 100] + " Hundred")
x %= 100
if x >= 20:
parts.append(tens[x // 10])
x %= 10
if x:
parts.append(ones[x])
return " ".join(parts)
units = ["", " Thousand", " Million", " Billion"]
res = []
i = 0
while num:
chunk = num % 1000
if chunk:
res.append(three(chunk) + units[i])
num //= 1000
i += 1
return " ".join(reversed(res))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1): at most four groups are processed.
💾 Space Complexity
O(1): constant besides the output.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the
num == 0case: the loop never runs and the result is an empty string, but the expected output isZero. - Not handling the teens 11..19 separately:
Elevencannot be written asTen One. - Missing the leading space in the unit suffixes: the
Thousandsuffix must carry a leading space so it joins cleanly with the group text. - Emitting zero-valued groups: for
1,000,001the middle group is 0 and must be skipped rather than producingZero Thousand.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.