Skip to content

Commit c574f3a

Browse files
author
Openset
committed
Add: integer_to_roman
1 parent 7962a2f commit c574f3a

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,14 @@
11
package integer_to_roman
2+
3+
func intToRoman(num int) string {
4+
base := [...]int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
5+
bs := [...]string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
6+
ans := ""
7+
for i, b := range base {
8+
for num/b > 0 {
9+
ans += bs[i]
10+
num -= b
11+
}
12+
}
13+
return ans
14+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,53 @@
11
package integer_to_roman
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input int
7+
expected string
8+
}
9+
10+
func TestIntToRoman(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: 3,
14+
expected: "III",
15+
},
16+
{
17+
input: 4,
18+
expected: "IV",
19+
},
20+
{
21+
input: 9,
22+
expected: "IX",
23+
},
24+
{
25+
input: 20,
26+
expected: "XX",
27+
},
28+
{
29+
input: 58,
30+
expected: "LVIII",
31+
},
32+
{
33+
input: 1994,
34+
expected: "MCMXCIV",
35+
},
36+
{
37+
input: 11111,
38+
expected: "MMMMMMMMMMMCXI",
39+
},
40+
}
41+
for _, tc := range tests {
42+
output := intToRoman(tc.input)
43+
if output != tc.expected {
44+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
45+
}
46+
}
47+
}
48+
49+
func BenchmarkIntToRoman(b *testing.B) {
50+
for i := 0; i < b.N; i++ {
51+
intToRoman(111111)
52+
}
53+
}

0 commit comments

Comments
 (0)