RosettaCodeData/Task/Roman-numerals-Decode/Go/roman-numerals-decode-2.go

38 lines
602 B
Go
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
package main
import (
"fmt"
)
2015-02-20 00:35:01 -05:00
var m = map[rune]int{
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
2013-04-10 23:57:08 -07:00
}
// function, per task description
func from_roman(roman string) (arabic int) {
last_digit := 1000
2015-02-20 00:35:01 -05:00
for _, r := range roman {
2013-04-10 23:57:08 -07:00
digit := m[r]
if last_digit < digit {
arabic -= 2 * last_digit
}
last_digit = digit
arabic += digit
}
return arabic
}
func main() {
// parse three numbers mentioned in task description
for _, roman_digit := range []string{"MCMXC", "MMVIII", "MDCLXVI"} {
fmt.Printf("%-10s == %d\n", roman_digit, from_roman(roman_digit))
}
}