Skip to content

Instantly share code, notes, and snippets.

@alexnoz
Created October 10, 2019 21:22
Show Gist options
  • Save alexnoz/63a2285b9568cd4a7cd69d9e6032ff38 to your computer and use it in GitHub Desktop.
Save alexnoz/63a2285b9568cd4a7cd69d9e6032ff38 to your computer and use it in GitHub Desktop.
Basic roman<->arabic numerals conversion utils
package main
import (
"sort"
"strings"
)
var romanIntMap = map[string]int{
"M": 1000,
"D": 500,
"C": 100,
"L": 50,
"X": 10,
"V": 5,
"I": 1,
"CM": 900,
"CD": 400,
"XC": 90,
"XL": 40,
"IX": 9,
"IV": 4,
}
func RomanToInt(roman string) int {
n := 0
var prev = string(roman[0])
for _, v := range roman {
s := string(v)
if prev != s && romanIntMap[prev] < romanIntMap[s] {
n -= romanIntMap[prev] * 2
}
n += romanIntMap[s]
prev = s
}
return n
}
func IntToRoman(n int) string {
vals := make([]int, len(romanIntMap))
intRomanMap := make(map[int]string, len(romanIntMap))
{
var i uint8 = 0
for k, v := range romanIntMap {
intRomanMap[v] = k
vals[i] = v
i++
}
}
// Sort keys desc
sort.Slice(vals, func (i, j int) bool { return vals[j] < vals[i] })
res := ""
for _, val := range vals {
sum, i := 0, 0
for n - val >= 0 {
i++
n -= val
sum += val
}
if i > 1 {
res += strings.Repeat(intRomanMap[sum], i)
} else {
res += intRomanMap[sum]
}
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment