leetcode: solve 'int to roman' problem in elixir

This commit is contained in:
Ivan R. 2024-06-11 19:22:13 +05:00
parent bb5eb9323f
commit 4e32127e79
Signed by: lumin
GPG key ID: E0937DC7CD6D3817
9 changed files with 112 additions and 0 deletions

View file

@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

View file

@ -0,0 +1,26 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where third-party dependencies like ExDoc output generated docs.
/doc/
# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Ignore package tarball (built via "mix hex.build").
integer_to_roman-*.tar
# Temporary files, for example, from tests.
/tmp/

View file

@ -0,0 +1,24 @@
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

View file

@ -0,0 +1,28 @@
defmodule IntegerToRoman.MixProject do
use Mix.Project
def project do
[
app: :integer_to_roman,
version: "0.1.0",
elixir: "~> 1.16",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end

View file

@ -0,0 +1,24 @@
defmodule IntegerToRomanTest do
use ExUnit.Case
doctest Solution
test "example 1" do
assert Solution.int_to_roman(3749) == "MMMDCCXLIX"
end
test "example 2" do
assert Solution.int_to_roman(58) == "LVIII"
end
test "example 3" do
assert Solution.int_to_roman(1994) == "MCMXCIV"
end
test "smallest number" do
assert Solution.int_to_roman(1) == "I"
end
test "largest number" do
assert Solution.int_to_roman(3999) == "MMMCMXCIX"
end
end

View file

@ -0,0 +1 @@
ExUnit.start()

View file

@ -0,0 +1,5 @@
# 12. Integer to Roman
[Leetcode](https://leetcode.com/problems/integer-to-roman/)
Given an integer, convert it to a Roman numeral.