Problem
Convert a non-negative integer num
to its English words representation.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraint
- 0 <= num <= 2^31 - 1
Solution
Method 1 - Using Lookup Table and Recursion 🏆
To solve the problem of converting a non-negative integer to its English words representation, we need to break down the number into manageable parts and process each part individually. This problem requires handling different ranges of numbers separately, such as units, tens, hundreds, thousands, millions, etc.
Video Explanation
Here is the video explanation:
Code
|
|
|
|
Some Test Cases
Some test cases for this problem:
- Start with easy case, just to see if it’s working properly like 1234
- Zero
- All numbers are the same digit like
1111
- All numbers are different digits
- A number with a lot of zeros like 500, 000; 30, 000, 100,000; 2000, 100, 90.
- At least one number in the teens (11-19)
- Numbers with zeros in the middle, like
500008
- Numbers less than 1000
- Numbers less than 100 like
89
Summary
Although this is our custom program, but in real life we shouldn’t reinvent the wheel and its best to use already-implemented functions to perform this. ICU4J contains a class com.ibm.icu.text. RuleBasedNumberFormat that can be used to perform this operation. It also supports languages other than English, and the reverse operation, parsing a text string to integer values.