-
Notifications
You must be signed in to change notification settings - Fork 1
/
roman-to-integer.go
41 lines (37 loc) · 934 Bytes
/
roman-to-integer.go
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
package main
func romanToInt(s string) int {
arr := []rune(s)
result := 0
rlen := len(arr)
for i := 0; i < rlen; i++ {
switch arr[i] {
case 'I':
if i < rlen - 1 && (arr[i + 1] == 'V' || arr[i + 1] == 'X') {
result--
} else {
result++
}
case 'V':
result += 5
case 'X':
if i < rlen - 1 && (arr[i + 1] == 'L' || arr[i + 1] == 'C') {
result -= 10
} else {
result += 10
}
case 'L':
result += 50
case 'C':
if i < rlen - 1 && (arr[i + 1] == 'D' || arr[i + 1] == 'M') {
result -= 100
} else {
result += 100
}
case 'D':
result += 500
case 'M':
result += 1000
}
}
return result
}