Expanded Numbers

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.

Example

  • 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.

function expandedForm(num) {
    let unit = 10
    let workNumber = num
    let s = ''
    do {
        const remainder = workNumber % unit
        if (remainder > 0) {
            s = s === '' ? `${remainder}` : `${remainder} + ${s}`
            workNumber -= remainder
        }
        unit *= 10
    } while (unit < num * 10)
    return s
}
Code language: JavaScript (javascript)

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.

Second approach

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!

function expandedForm(num) {
    const numArray = num.toString().split("").reverse()
    return numArray.reduce((result, current, index) => {
        if (current === '0') {
            return result
        }
        const currentValue = (parseInt(current) * 10 ** index).toString()
        return result === '' ? currentValue : `${currentValue} + ${result}`
    }, '')
}
Code language: JavaScript (javascript)

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.