voughtdq

voughtdq

Given an integer, produce a list of its digits

I need to turn an integer into a list of digits.

For example, given 1234 as input, the output should be [1, 2, 3, 4].

I am doing this right now, but it looks ugly and might even be inefficient.

  def get_check_digit(digits) when is_binary(digits) or is_integer(digits) do
    digits
    |> to_charlist()
    |> Enum.map(fn char ->
      {integer, []} = :string.to_integer([char])
      integer
    end)
    |> get_check_digit()
  end

  def get_check_digit(digits) when is_list(digits) do
    ...
  end

Any tips?

Marked As Solved

tovarchristian21

tovarchristian21

How about Integer.digits/2 ?

Also Liked

wolf4earth

wolf4earth

Integer.digits/2 is certainly the easiest way to do this but I took a stab at this and wrote two versions:

Make use of codepoints

The first version is super short and basically makes use of the fact that charlists boil down to a list of integers (where the characters have their corresponding ASCII values).

iex> 1234 |> to_charlist() |> Enum.map(& &1 - ?0)
[1, 2, 3, 4]

By converting the number to a charlist, we have a list of codepoints. From here we can subtract the codepoint value of 0 (?0 which is 48) to get the actual numerical value.

Use math and recursion

The second solution uses a combination of integer division and the modulo operation. But see for yourself:

defmodule Digits do
  def digits(number) when number < 0, do: digits(-number)

  def digits(number) when is_integer(number) do
    calc(number, [])
  end

  defp calc(digit, digits)
    when digit < 10,
    do: [digit | digits]

  defp calc(number, digits) do
    digit = Integer.mod(number, 10)

    number
    |> div(10)
    |> calc([digit | digits])
  end
end

IO.inspect Digits.digits(1234), charlists: :as_lists

Here we get a single digit by doing number % 10 (which is Integer.mod/2 in Elixir), then we do the same for the next digit by dividing through 10. If we reach anything smaller than 10 we add it to the list and were done.

voughtdq

voughtdq

Nice! Thanks

rvirding

rvirding

Creator of Erlang

Am I missing something here? :smile: Isn’t :erlang.integer_to_list/1/2 the easiest and fastest? Though it would give a “bad” error value if the argument is not an integer.

fuelen

fuelen

:erlang.integer_to_list returns charlist

> :erlang.integer_to_list(123123)
'123123'
> Integer.digits(123123)
[1, 2, 3, 1, 2, 3]
rvirding

rvirding

Creator of Erlang

Yes, I realised that later. :smile:

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement