For today we have a number problem. The idea is to take an integer and return the expanded form. This problem wasn’t particularly difficult or tricky and honestly finding a wrong approach would have been harder than finding two correct approaches.
- Input: 12, Output “10 + 2”
- Input 42, Output “40 + 2”
Expanded Numbers first approach
This is my least favorite method. We start by calculating the remainder using the lowest 10s, then add that reminder to the work string. We increase the units and remove the remainder from the work number and continue until our units are greater than the initial number.
I definitely explained that wrong, but honestly, I can’t for the life of me figure out what the 10s/100s thingy is called at the moment. So let’s look at the code instead.
This approach works, and while it’s not too convoluted I did not like it. It feels a little too complicated for the problem and wrapping your head around the logic takes a minute. We are also using modulus, and I think this problem can be solved without it.
My second approach is easier to understand and thus is my favorite. The idea is simple,
- you take the number
- convert it to a string
- split into a list
- reverse the list
- reduce the list
- use the index to get the power of 10 you need to multiply the number to get the zeros
Ok, maybe not so easy to understand. But code to the rescue!
No modulus in sight. Honestly, as I type this out both approaches require a minute to fully grok, but I believe the second is slightly easier to get.
But at the end of the day what we want is a solution that solves the problem. Both of these solutions do that so I’d accept both if I was interviewing a candidate.
I found this problem quite interesting and am honestly tempted to see if I can find a more elegant solution. But that will be for a later post. For now, I’m happy with these two answers.
You should try these in whatever language you code in and if you do send me your code, I’d love to see it. You can send it to me on Twitter @phoexer and as always happy coding.