my-solutions/leetcode/0012-integer-to-roman/elixir/lib/integer_to_roman.ex

25 lines
754 B
Elixir
Raw Normal View History

defmodule Solution do
@spec int_to_roman(num :: integer) :: String.t()
def int_to_roman(num) do
thousands = div(num, 1000)
hundreds = div(rem(num, 1000), 100)
tens = div(rem(num, 100), 10)
String.duplicate("M", thousands) <>
to_roman(hundreds, "C", "D", "M") <>
to_roman(tens, "X", "L", "C") <>
to_roman(rem(num, 10), "I", "V", "X")
end
@spec to_roman(num :: integer, one :: String.t(), five :: String.t(), ten :: String.t()) ::
String.t()
defp to_roman(num, one, five, ten) do
case num do
x when x <= 3 -> String.duplicate(one, x)
x when x == 4 -> one <> five
x when x > 4 and x <= 8 -> five <> String.duplicate(one, x - 5)
x when x > 8 -> one <> ten
end
end
end