Digits back to integers in Julia
Mar 27, 2016 · 259 words · 2 minutes read
Sometimes useful to split an integer into its digits and often its desirable to revert the process (digits back to an integer). The first part is trivial using the base function digits
. Unfortunately the second part has no base function.
Integer to digits
The digits function in base takes an integer (and optionally a base and padding) and returns an array of the digits of the integer.
julia> digits(1234)
4-element Array{Int64,1}:
4
3
2
1
Digits back to integer
Since there isn’t a base function we have to do this manually. Starting with an array we can easily reduce the collection to a string.
julia> a = digits(1234);
julia> num = reduce(string, a)
"4321"
Notice the digits in the string are reversed. We can reverse the string and then just convert to an integer.
julia> parse(Int, reverse(num))
1234
1-element case
Everything above works well if our initial number has multiple digits. More specifically reduce(string, a)
doesn’t return a string if a
is a 1-element array.
julia> a = digits(5)
1-element Array{Int64,1}:
5
julia> num = reduce(string, a)
5
julia> typeof(num)
Int64
This is a bit of a problem because we don’t always know the number of digits in the array and we can’t convert an integer to another integer.
julia> parse(Int, num)
ERROR: MethodError: `parse` has no method matching parse(::Type{Int64}, ::Int64)
Rolling our own function
Putting all of this together we have a simple function.
julia> function digits2integer(a)
x = reduce(string, reverse(a))
if length(a)==1
return x
end
parse(Int, x)
end
julia> digits2integer(digits(5234)) == 5234
true
julia> digits2integer(digits(7)) == 7
true