LeetCode 273: Integer to English Words
Take a look at what translating
1241234113

results in when aligned slightly differently
                       One       Billion 
Two  Hundred   Forty   One       Million 
Two  Hundred   Thirty  Four      Thousand 
One  Hundred           Thirteen  

you can see that there are several patterns here.

Every number can be chunked into groups of 3 digits like this 1,241,234,113.

Each chunk has a different value for the last column, which is one of &quot;Billion&quot;, &quot;Million&quot;, etc.

Within each chunk, there is one digit at the hundreds place.

Within each chunk, the last 2 digits have a special case till 20, otherwise it's a special word for the ten's place, and the one's place.


So the only variables you need are just
std::string const till_twenty[20] = {&quot;&quot;, &quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot;, &quot;Five&quot;, &quot;Six&quot;, &quot;Seven&quot;, &quot;Eight&quot;, &quot;Nine&quot;, &quot;Ten&quot;, &quot;Eleven&quot;, &quot;Twelve&quot;, &quot;Thirteen&quot;, &quot;Fourteen&quot;, &quot;Fifteen&quot;, &quot;Sixteen&quot;, &quot;Seventeen&quot;, &quot;Eighteen&quot;, &quot;Nineteen&quot;};
std::string const tens_place[10] = {&quot;&quot;, &quot;Ten&quot;, &quot;Twenty&quot;, &quot;Thirty&quot;, &quot;Forty&quot;, &quot;Fifty&quot;, &quot;Sixty&quot;, &quot;Seventy&quot;, &quot;Eighty&quot;, &quot;Ninety&quot;};
std::string const thousands[4] = {&quot;&quot;, &quot;Thousand&quot;, &quot;Million&quot;, &quot;Billion&quot;};

Note that I've renamed the variables slightly, and made them const. Also, there's no need for the word Zero, since that will only be written if the entire number is 0.
Now you can build up the functions for the 3 digit chunks
//for the first digit    
std::string hundreds_place(int n) {
   return n ? till_twenty[n] + &quot; Hundred &quot; : &quot;&quot;;
}
  
// for the 2nd and 3rd digit  
std::string ones_and_tens_place(int n) {
    return n &lt;= 20 ? till_twenty[n] : tens_place[n / 10] + 
                                      (n % 10 ? &quot; &quot; + till_twenty[n % 10] : &quot;&quot;)
}

// putting all 3 digits together
std::string by_hundreds(int n) {
    return hundreds_place(n / 100) + ones_and_tens_place(n % 100);
}

Now you can recursively build the 3 digit numbers by keeping track of which power of 1000 is being currently processed
std::string by_thousands(int n, int i) {    // i keeps track of the chunk
    return n ? by_thousands(n / 1000, i + 1) + 
               by_hundreds(n % 1000) + &quot; &quot; 
               + thousands[i] + &quot; &quot;
             : &quot;&quot;;
}

and then finally it can all be put together
std::string numberToWords(int num) {
    std::string res = num ? by_thousands(num, 0) : &quot;Zero  &quot;;
    // with a bit of processing to get rid of trailing spaces
    return res.substr(0, res.length() - 2);        
}