Opening the reading…
Opening the reading…
RECURSION & BACKTRACKING › RECURSION PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →English number names repeat the same rules every three digits. A group such as 567 is always written as Five Hundred Sixty Seven, whether it appears alone, after Thousand, or after Million. The group changes its scale word, but its internal spelling never changes.
Separate the number into groups from right to left: units, thousands, millions, and billions. Translate each nonzero group with a helper for values below 1000, then place its scale word after it. Processing from the smallest group upward means each new group can be placed before the text already built.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(1) | The loop examines at most four groups, and the helper handles at most three digits per group. The lookup arrays and the amount of text are bounded by the fixed 32-bit input range, so no operation grows beyond a constant number of characters. |
| Space | O(1) extra | The output string is required output and is excluded from the extra-space bound. The lookup arrays, the current group, and temporary helper strings are all bounded by the four possible groups and three digits per group, so the working memory remains constant. |
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string numberToWords(int num) {
if (num == 0) return "Zero";
vector<string> thousands = {"", "Thousand", "Million", "Billion"};
string result;
int scale = 0;
while (num > 0) {
int group = num % 1000;
if (group != 0) {
result = helper(group) + thousands[scale] + " " + result;
}
num /= 1000;
scale++;
}
while (result.back() == ' ') result.pop_back();
return result;
}
private:
string helper(int num) {
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 result;
if (num >= 100) {
result += below20[num / 100] + " Hundred ";
num %= 100;
}
if (num >= 20) {
result += tens[num / 10] + " ";
num %= 10;
}
if (num > 0) {
result += below20[num] + " ";
}
return result;
}
};The order of the two divisions is important. The remainder extracts the group that belongs to the current scale, while division advances to the next group. Because this scan discovers units before thousands and millions, the newly translated text is placed before result. A zero group is skipped entirely; its position is already represented by the next scale index.