⚡Flashcard Drill➔
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

  1. Split the number into groups of three digits from the least significant side, labelled Thousand, Million, and Billion.
  2. Write a helper three(x) that handles 0..999: hundreds with the word Hundred, then the tens or teens table, then the ones digit.
  3. For each group, if it is non-zero, append its words plus the group suffix; then reverse the collected groups.
  4. Special-case num == 0 to return Zero, 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 == 0 case: the loop never runs and the result is an empty string, but the expected output is Zero.
  • Not handling the teens 11..19 separately: Eleven cannot be written as Ten One.
  • Missing the leading space in the unit suffixes: the Thousand suffix must carry a leading space so it joins cleanly with the group text.
  • Emitting zero-valued groups: for 1,000,001 the middle group is 0 and must be skipped rather than producing Zero Thousand.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Math & Geometry Problems