Skip to content

Instantly share code, notes, and snippets.

@swift-student
Last active February 26, 2020 16:28
Show Gist options
  • Save swift-student/0f9e25b501280caa84830d65f80d5323 to your computer and use it in GitHub Desktop.
Save swift-student/0f9e25b501280caa84830d65f80d5323 to your computer and use it in GitHub Desktop.

My first idea to epand an integer would be to use the modulo operator starting with 10 and increasing by a power of 10 each time. So if the input was 987 I would do 987 % 10 and get 980. Then I would add 7 to my array, and subtract 7 from my input integer as well. The next time through the loop I would do 980 % 100 and get 80, which should be added to the beginning of my array, since the arrays should be ordered from largest component to smallest. This would repeat one more time with 900 % 1000 which would give me 900. Once I add 900 to my array and subtract it from my integer, my integer would be at 0. This will be my exit condition for my loop.

One thing to consider would be negative input numbers as well as 0. I will have to figure out to handle these conditions after I get it working with positive integers.

After testing my code, it occured to me that by using a repeat while loop, I could get my function to return an array of [0] by letting it execute the loop once with an input value of 0 before evaluating. Negative integers also seem to work fine, so no work to do there. I believe my execution is also efficient, while being simple and easy to understand. Here is what my final function looks like:

func expandTheNumber(_ num: Int) -> [Int] {
    var num = num
    var components = [Int]()
    var divisor = 10
    
    repeat {
        let component = num % divisor
        components.insert(component, at: 0)
        num -= component
        divisor *= 10
    } while num != 0
    
    return components
}

expandTheNumber(987)  // [900, 80, 7]
expandTheNumber(-987) // [-900, -80, -7]
expandTheNumber(0)    // [0]
expandTheNumber(5280) // [5000, 200, 80, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment