Skip to content

Commit ecd6be4

Browse files
solved roman to integer
1 parent 373c7ff commit ecd6be4

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

roman-to-integer/roman_to_integer.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package romantointeger
2+
3+
import (
4+
"strings"
5+
)
6+
7+
func RomanToInt(s string) int {
8+
romanInt := 0
9+
10+
// uppercase input
11+
stringUpperCases := strings.ToUpper(s)
12+
13+
// symbol romawi
14+
symbol := map[byte]int{
15+
'I': 1,
16+
'V': 5,
17+
'X': 10,
18+
'L': 50,
19+
'C': 100,
20+
'D': 500,
21+
'M': 1000,
22+
}
23+
24+
// loop stringUpperCase and match with symbol
25+
index := 0
26+
for index < len(stringUpperCases) {
27+
if index+1 < len(stringUpperCases) {
28+
if symbol[stringUpperCases[index]] < symbol[stringUpperCases[index+1]] {
29+
romanInt += symbol[stringUpperCases[index+1]] - symbol[stringUpperCases[index]]
30+
index += 2
31+
continue
32+
} else {
33+
romanInt += symbol[stringUpperCases[index]]
34+
}
35+
} else {
36+
romanInt += symbol[stringUpperCases[index]]
37+
}
38+
39+
index += 1
40+
}
41+
42+
return romanInt
43+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package romantointeger_test
2+
3+
import (
4+
rti "letcode/roman-to-integer"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestRomanToInt(t *testing.T) {
11+
testCases := []struct {
12+
Name string
13+
Symbol string
14+
Expectation int
15+
}{
16+
{
17+
Name: "Test 1",
18+
Symbol: "III",
19+
Expectation: 3,
20+
}, {
21+
Name: "Test 2",
22+
Symbol: "LVIII",
23+
Expectation: 58,
24+
}, {
25+
Name: "Test 3",
26+
Symbol: "MCMXCIV",
27+
Expectation: 1994,
28+
}, {
29+
Name: "Test 4",
30+
Symbol: "mcmxciv",
31+
Expectation: 1994,
32+
},
33+
}
34+
35+
for _, testCase := range testCases {
36+
t.Run(testCase.Name, func(t *testing.T) {
37+
actual := rti.RomanToInt(testCase.Symbol)
38+
assert.Equal(t, testCase.Expectation, actual)
39+
})
40+
}
41+
}
42+
43+
func BenchmarkRomanToInt(b *testing.B) {
44+
for i := 0; i < b.N; i++ {
45+
rti.RomanToInt("III")
46+
}
47+
}

0 commit comments

Comments
 (0)