Last active
July 14, 2023 19:27
-
-
Save rabestro/577796f68281878f426175dd4b49b0c0 to your computer and use it in GitHub Desktop.
Roman Numerals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package romannumerals provides methods for manipulating numbers into roman numerals | |
package romannumerals | |
import "errors" | |
type RomanNumeral struct { | |
Value int | |
Symbol string | |
} | |
// RomanNumerals is the mapping between numbers and their corresponding Roman numerals | |
var RomanNumerals = []RomanNumeral{ | |
{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"}, | |
} | |
const MINIMUM = 1 | |
const MAXIMUM = 3999 | |
func validateRange(number int) error { | |
if number < MINIMUM || number > MAXIMUM { | |
return errors.New("number has to be in range [1..3999]") | |
} | |
return nil | |
} | |
func arabicToRoman(number int) string { | |
roman := "" | |
for _, numeral := range RomanNumerals { | |
for number >= numeral.Value { | |
number -= numeral.Value | |
roman += numeral.Symbol | |
} | |
} | |
return roman | |
} | |
// ToRomanNumeral converts an integer to its roman numeral string equivalent | |
func ToRomanNumeral(number int) (string, error) { | |
if err := validateRange(number); err != nil { | |
return "", err | |
} | |
return arabicToRoman(number), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment