Skip to content

Instantly share code, notes, and snippets.

@ShawnSWu
Created July 8, 2022 01:35
Show Gist options
  • Save ShawnSWu/63c0e1d8ecbcea0bfaa91924b7642a7c to your computer and use it in GitHub Desktop.
Save ShawnSWu/63c0e1d8ecbcea0bfaa91924b7642a7c to your computer and use it in GitHub Desktop.
Roman to Integer
func romanToInt(input string) int {
currentPoint := len(input) - 1
result := 0
for currentPoint > 0 {
right := mapInt(getChar(currentPoint, input))
left := mapInt(getChar(currentPoint-1, input))
if right == left {
if result == 0 {
result += right + left
} else {
result += left
}
} else {
if currentPoint != (len(input) - 1) {
right = result //若當前指針不是最後一個值,則將目前的result當作right去跟left計算
}
if right > left {
result = right - left
} else {
result = right + left
}
}
currentPoint -= 1
}
return result
}
func getChar(v int, input string) rune {
inputRunes := []rune(input)
return inputRunes[v]
}
func mapInt(v rune) int {
romanNumberMap := map[rune]int{
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
return romanNumberMap[v]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment