mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 08:27:30 +08:00
30 lines
418 B
Go
30 lines
418 B
Go
package leetcode
|
|
|
|
var roman = map[string]int{
|
|
"I": 1,
|
|
"V": 5,
|
|
"X": 10,
|
|
"L": 50,
|
|
"C": 100,
|
|
"D": 500,
|
|
"M": 1000,
|
|
}
|
|
|
|
func romanToInt(s string) int {
|
|
if s == "" {
|
|
return 0
|
|
}
|
|
num, lastint, total := 0, 0, 0
|
|
for i := 0; i < len(s); i++ {
|
|
char := s[len(s)-(i+1) : len(s)-i]
|
|
num = roman[char]
|
|
if num < lastint {
|
|
total = total - num
|
|
} else {
|
|
total = total + num
|
|
}
|
|
lastint = num
|
|
}
|
|
return total
|
|
}
|