Sha256: ac8e3d4686fe5812b1a05623a9554bae2cde48e7fd22b147aae12938c4529983

Contents?: true

Size: 1.04 KB

Versions: 327

Compression:

Stored size: 1.04 KB

Contents

defmodule Hexadecimal do
  @base 16
  @hex_table String.split("0123456789abcdef", "", trim: true)
               |> Enum.with_index
               |> Enum.into(%{})

  @doc """
    Accept a string representing a hexadecimal value and return the
    corresponding decimal value.
    It returns the integer 0 if the hexadecimal is invalid.
    Otherwise returns an integer representing the decimal value.

    ## Examples

      iex> Hexadecimal.to_decimal("invalid")
      0

      iex> Hexadecimal.to_decimal("af")
      175

  """

  @spec to_decimal(binary) :: integer
  def to_decimal(hex) do
    if invalid?(hex) do
      0
    else
      hex
        |> String.downcase
        |> String.reverse
        |> String.split("", trim: true)
        |> hex_to_int(0, 0)
    end
  end

  defp invalid?(hex) do
    String.match?(hex, ~r/[^0-9a-fA-F]/)
  end

  defp hex_to_int([], acc, _), do: round(acc)
  defp hex_to_int([char|hex], acc, power) do
    acc = acc + Map.get(@hex_table, char) * :math.pow(@base, power)
    hex_to_int(hex, acc, power + 1)
  end
end

Version data entries

327 entries across 327 versions & 1 rubygems

Version Path
trackler-2.2.1.49 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.48 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.47 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.46 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.45 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.44 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.43 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.42 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.41 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.40 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.39 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.38 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.37 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.36 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.35 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.34 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.33 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.32 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.31 tracks/elixir/exercises/hexadecimal/example.exs
trackler-2.2.1.30 tracks/elixir/exercises/hexadecimal/example.exs