Roman Numerals Encode And Decode

Encode integers by greedy subtraction over descending numeral pairs, then decode by longest-prefix matching the same table back.

GoData Integrity

Code

gosnippet
53 lines
package main

import (
	"fmt"
	"strings"
)

// Roman numerals 专用表:减写组合必须排在单符号之前,贪心扣除才不会出错
var numerals = []struct {
	arabic int
	symbol string
}{
	{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},
	{100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"},
	{10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
}

func encode(n int) string {
	var b strings.Builder
	for _, v := range numerals {
		for n >= v.arabic {
			b.WriteString(v.symbol)
			n -= v.arabic
		}
	}
	return b.String()
}

func decode(s string) int {
	total := 0
	for len(s) > 0 {
		matched := false
		for _, v := range numerals {
			if strings.HasPrefix(s, v.symbol) {
				total += v.arabic
				s = strings.TrimPrefix(s, v.symbol)
				matched = true
				break
			}
		}
		if !matched {
			panic("invalid numeral: " + s)
		}
	}
	return total
}

func main() {
	for _, n := range []int{2026, 1994, 4} {
		r := encode(n)
		fmt.Printf("%d -> %s -> %d\n", n, r, decode(r))
	}
}

Inside the snippet

Structurally, expect the functions encode, decode and main and nothing else.

for _, v := range numerals is the loop that carries the per-item work.

Caveats

  • Entirely standard-library — copy it in and it runs.

Putting it to use

Entry signature: func encode(n int) string

main sequences encode and decode; executing the file runs that flow once.

The operative lines

for _, n := range []int{2026, 1994, 4} {
	r := encode(n)
	fmt.Printf("%d -> %s -> %d\n", n, r, decode(r))
}
for _, v := range numerals {
	for n >= v.arabic {
		b.WriteString(v.symbol)
		n -= v.arabic
	}
}
for _, v := range numerals {
	if strings.HasPrefix(s, v.symbol) {
		total += v.arabic
		s = strings.TrimPrefix(s, v.symbol)
		matched = true
		break
	}
}

Interactive Tools for This Topic

FAQ

How do you run Roman Numerals Encode And Decode?
Nothing to install first — run the file and the program does the rest.