-
Notifications
You must be signed in to change notification settings - Fork 1
/
romanToInt.go
45 lines (44 loc) · 765 Bytes
/
romanToInt.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
42
43
44
45
package romantointeger
func romanToInt(s string) int {
if l := len(s); l >= 1 {
var last, current, result int
for i := 0; i < l; i++ {
switch s[i] {
case 'M':
result += 1000
current = 7
case 'D':
result += 500
current = 6
case 'C':
result += 100
current = 5
case 'L':
result += 50
current = 4
case 'X':
result += 10
current = 3
case 'V':
result += 5
current = 2
default: // 'I'
result++
current = 1
}
if last != 0 && last < current {
switch last*10 + current {
case 12, 13: // "IV"/"IX"
result -= 2
case 34, 35: // "XL"/"XC"
result -= 20
case 56, 57: // "CD"/"CM"
result -= 200
}
}
last = current
}
return result
}
return 0
}