Link: https://leetcode.com/problems/integer-to-english-words/
Solution:
Topics: math
Intuition
I consider there to be two parts to this problem. The key insight, and then the implementation. The implementation typically writes itself, but in this case there is a very clever trick we can use that will make the code clean.
The key insight is that the number must be processed in adjacent triplets of digits. For example:
num = 200200
word = (two hundred thousand) (two hundred)
if we look at the 3 digits from the end, the number is 200.
the next 3 digits are also 200. The only difference is that the next
triplet represents thousands.
The same rules apply for subsequent triplets (million and billion)
So lets move on to how we can process a triplet of digits. The third digit (from the end) always represents hundreds, the second is tens and the third is ones. There is only one edge case(s)
to worry about, which is if the value of the first two digits is greater than 9 and less than twenty. In that case, the first two digits form ten, eleven, twelve...
. And of course adding the units at the end thousand, million, billion
.
So the logic is basically solved, but the implementation not as clear. Of course we will need hash maps to convert numbers to words, but what is the best way to process each triplet in the correct order?
My first solution to this problem was to convert the number into a string, reverse it, add leading zeros if needed , and then process each slice of three. For example:
This of course works, but its kind of annoying and riddled with edge cases. The much cleaner and more interesting implementation involves extracting each triplet directly from the number using modulus operations and integer division. How?
Now we can use this method of processing to build out our parsing logic:
Implementation
Mnemonic
You have long number in front of you. To delete all digits except the last 3, we cover the rest with a %1000
. To delete the last 3 digits, we cover them with a //1000.
Visual
Review 1
Not very difficult algorithmically but the implementation is pretty interesting.