- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12.clj
45 lines (38 loc) · 1.35 KB
/
12.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
(nsclojure.12
"Leetcode: 12\n
Name: Integer to Roman\n"
(:require [clojure.test :refer [deftest is run-tests]]))
(defonceroman-symbols
[["M"1000] ["CM"900] ["D"500] ["CD"400] ["C"100] ["XC"90]
["L"50] ["XL"40] ["X"10] ["IX"9] ["V"5] ["IV"4] ["I"1]])
(defnint-to-roman
"Convert an integer to its Roman numeral representation.
Args:
num - An integer value to convert (1 <= num <= 3999).
Returns:
A string representing the Roman numeral equivalent of the integer.
Examples:
(int-to-roman 4) ;=> \"IV\"
(int-to-roman 9) ;=> \"IX\"
(int-to-roman 1994) ;=> \"MCMXCIV\""
[num]
{:pre [(and (integer? num) (<=1 num 3999))]}
(loop [number num
result ""]
(if (zero? number)
result
(let [[symbol value] (first (filter #(<= (second %) number) roman-symbols))]
(recur (- number value)
(str result symbol))))))
(deftesttest-int-to-roman
(is (= (int-to-roman1) "I"))
(is (= (int-to-roman4) "IV"))
(is (= (int-to-roman9) "IX"))
(is (= (int-to-roman58) "LVIII"))
(is (= (int-to-roman1994) "MCMXCIV"))
(is (= (int-to-roman3999) "MMMCMXCIX"))
(is (= (int-to-roman1) "I"))
(is (= (int-to-roman3999) "MMMCMXCIX"))
(is (thrown? AssertionError (int-to-roman0)))
(is (thrown? AssertionError (int-to-roman4000))))
(run-tests)