【发布时间】:2025-11-30 05:35:01
【问题描述】:
面临错误 Panic Runtime Error index out of range [3] with length 3。以下错误似乎表明索引超出范围或长度
panic: runtime error: index out of range [3] with length 3
main.romanToInt(0xc000022080, 0x3, 0x8)
solution.go, line 15
main.__helper__(...)
solution.go, line 30
main.main()
solution.go, line 58
func romanToInt(s string) int {
romanNum := map[byte]int{
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
var sum int = 0
for i := 0; i <= len(s); i++ {
currentInt := romanNum[s[i]]
nextInt := romanNum[s[i+1]]
if currentInt < nextInt {
sum = sum + (nextInt - currentInt)
i += 1
} else {
sum = sum + currentInt
}
}
return sum
}
错误指向
nextInt := romanNum[s[i+1]]
【问题讨论】:
标签: arrays loops dictionary go slice