Convert integers to roman numerals in Go
Converting an integer to a Roman numeral can be achieved in Go with just a few lines of code
This approach uses a lookup table for the conversion between digit and numeral
which helps us easily insert the appropriate numeral (or numerals) as many times
as possible while reducing the target number
by the same amount.
func integerToRoman(number int) string {
maxRomanNumber := 3999
if number > maxRomanNumber {
return strconv.Itoa(number)
}
conversions := []struct {
value int
digit 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"},
}
var roman strings.Builder
for _, conversion := range conversions {
for number >= conversion.value {
roman.WriteString(conversion.digit)
number -= conversion.value
}
}
return roman.String()
}
The Roman numeral system consists of the symbols which are I, V, X, L, C, D, and M which stand for 1, 5, 10, 50, 100, 500, and 1,000 respectively. These symbols are combined through a simple formula to produce other values. A symbol placed after another of equal or greater value adds its value (e.g., III = 3 and XX = 20), while symbol placed before one of greater value subtracts its value (e.g., IV = 4, XL = 40). Numbers greater than 3,999 cannot be represented in the Roman system so they are returned as stringified integers.
func main() {
fmt.Println(integerToRoman(300))
fmt.Println(integerToRoman(45))
fmt.Println(integerToRoman(1238))
fmt.Println(integerToRoman(3259))
}
Thanks for reading, and happy coding!