Skip to content

Commit a96e1ee

Browse files
committed
feat(map): roman to int
1 parent 7781831 commit a96e1ee

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

0013.roman-to-integer/main.go

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func romanToInt(s string) int {
6+
m := map[string]int{
7+
"M": 1000,
8+
"CM": 900,
9+
"D": 500,
10+
"CD": 400,
11+
"C": 100,
12+
"XC": 90,
13+
"L": 50,
14+
"XL": 40,
15+
"X": 10,
16+
"IX": 9,
17+
"V": 5,
18+
"IV": 4,
19+
"I": 1,
20+
}
21+
num := 0
22+
for {
23+
if len(s) == 0 {
24+
break
25+
}
26+
ss := ""
27+
if len(s) > 1 {
28+
ss = s[0:2]
29+
}
30+
if ss == "CM" || ss == "CD" || ss == "XC" || ss == "XL" || ss == "IX" || ss == "IV" {
31+
num += m[ss]
32+
s = s[2:]
33+
} else {
34+
ss = s[0:1]
35+
num += m[ss]
36+
s = s[1:]
37+
}
38+
}
39+
return num
40+
}
41+
42+
func main() {
43+
s := "IV"
44+
fmt.Println(romanToInt(s))
45+
}

0 commit comments

Comments
 (0)