Daily bit(e) of C++ | English Numbers
Daily bit(e) of C++, The common C++ interview problem: English Numbers
Today we will look at a common C++ interview problem: English Numbers.
Given an unsigned integer, transform it into an English textual representation.
Before you continue reading the solution, try to solve it yourself. Here is a Compiler Explorer link with a couple of test cases: https://compiler-explorer.com/z/vY3463hKd.
Solution
This problem doesn't contain any tricks or complex algorithms. The only aim of this problem is to test diligence.
As such, it is worthwhile first to write down the complete specification.
The conversion is periodic, with a period of 1000, non-zero periods form output in the form "X Magnitude", e.g. "42 Million". The X is the conversion of the 0-999 value into a text form.
Numbers 0-99 have a semi-regular format:
0..14 are irregular: "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen".
15..19, and 20-99 are regular, using the common prefixes: "Twen", "Thir", "For", "Fif", "Six", "Seven", "Eigh", and "Nine".
15..19, the prefix is based on the second digit and is followed by "teen".
20..99, the prefix is based on the first digit and is followed by "ty". The second digit is based on the 0..9 irregular range (omitting zero).
We can transform this directly into code:
Hundreds are represented using a single digit number based on 0..9 irregular range (omitting entirely when zero).
Finally, we can process the number, three least significant decimal digits at a time, adding the corresponding magnitude descriptor.