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
| package main
import "fmt"
func romanToInt(s string) int { romanMap := map[byte]int{ 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, }
result := 0 prevValue := 0
for i := len(s) - 1; i >= 0; i-- { currentValue := romanMap[s[i]]
if currentValue < prevValue { result -= currentValue } else { result += currentValue }
prevValue = currentValue }
return result }
func main() { romanNumeral := "IX"
result := romanToInt(romanNumeral)
fmt.Printf("罗马数字 %s 转换为整数是 %d\n", romanNumeral, result) }
|