Integer to English Words

Recurse over thousands groups — each group of 3 digits converted to "hundreds tens units", suffixed by "Thousand"/"Million"/"Billion".

Hard
Time O(log n) Space O(log n)
LeetCode
6 min read
math string recursion

Problem#

Convert a non-negative integer to its English-word representation.

Examples#

  • 123"One Hundred Twenty Three".
  • 12345"Twelve Thousand Three Hundred Forty Five".

Constraints#

  • 0 <= num <= 2^31 - 1.

Approach#

Split the number into groups of three digits (thousands). For each group emit “hundreds tens units” via lookup tables. Append the magnitude suffix per group.

Solution#

Integer to English Words
class Solution {
vector<string> below20 = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
vector<string> tens = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
string under1000(int n) {
string s;
if (n >= 100) { s += below20[n / 100] + " Hundred"; n %= 100; if (n) s += ' '; }
if (n >= 20) { s += tens[n / 10]; n %= 10; if (n) s += ' '; }
if (n > 0 && n < 20) s += below20[n];
return s;
}
public:
string numberToWords(int num) {
if (num == 0) return "Zero";
vector<string> suffix = {"", " Thousand", " Million", " Billion"};
string out;
int idx = 0;
while (num > 0) {
int part = num % 1000;
if (part) {
string chunk = under1000(part) + suffix[idx];
out = chunk + (out.empty() ? "" : " ") + out;
}
num /= 1000;
++idx;
}
return out;
}
};

Editorial#

The trick is keeping spaces clean. Build each thousand-group’s chunk, then prepend it to the accumulator with a single space separator only when both sides are non-empty. The num == 0 corner case must be special-cased — every other digit would produce an empty string.

Complexity#

  • Time: O(log n).
  • Space: O(log n) for the output.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.