Search code examples
arraysintegerjuliadigits

Is there a quick way concat the values returned by Julia's digits() method back into it's original number?


I really like Julia's Digits function which will return an array of the individual digits that make up the input integer (See code example). My question is, once you have this array, is there an easy way to join the individual values back into the original value passed into digits?

Now, I suppose I could just take each integer's index value and multiply by it's corresponding power of 10 and modify the array in place. Then I could use sum on the array, but is there a better way to do it?

I.E

function getDigits(x)
    return digits(x)
end

Julia> getDigits(1234)
4-element Array{Int64,1}:
4
3
2
1

function joinDigits(digitArray)
     for i in 0:length(digitArray)-1
         digitArray[i+1] = digitArray[i+1] * 10 ^ i
     end
     return sum(digitArray)

Julia> joinDigits([4,3,2,1])
1234

Solution

  • foldr((rest, msd) -> rest + 10*msd,x) is a one liner that does the same thing. It's terse, but probably not as clean as the for loop.