How to convert number to roman numerals

Apr 15, 2019 11:21 · 314 words · 2 minute read

Summary

Converting integers to markdown is fairly simple.

Here are 13 roman numerals and their decimal equivalent.

DecimalRoman
1I
4IV
5V
9IX
10X
40XL
50L
90XC
100C
400CD
500D
900CM
1000M

The process is as follows, for any given decimal number X:

  1. From the table shown above, find the highest decimal value, V, that is less than or equal to decimal number X i.e. V<=X.
  2. Write the roman numeral N that was found and subtract its value V from X:

Integer to Roman in golang.

package main

import (
	"fmt"
)

func main() {

	for i := 0; i < 100; i++ {
		fmt.Println(i, intToRoman(i))
	}

}

func intToRoman(num int) string {
	values := []int{
		1000, 900, 500, 400,
		100, 90, 50, 40,
		10, 9, 5, 4, 1,
	}

	symbols := []string{
		"M", "CM", "D", "CD",
		"C", "XC", "L", "XL",
		"X", "IX", "V", "IV",
		"I"}
	roman := ""
	i := 0
	for num > 0 {
		k := num / values[i]
		for j := 0; j < k; j++ {
			roman += symbols[i]
			num -= values[i]
		}
		i++
	}
	return roman
}

Lets annotate this code, to make things a bit more clear.


func intToRoman(num int) string {
	values := []int{
		1000, 900, 500, 400,
		100, 90, 50, 40,
		10, 9, 5, 4, 1,
	}

	symbols := []string{
		"M", "CM", "D", "CD",
		"C", "XC", "L", "XL",
		"X", "IX", "V", "IV",
		"I"}
	roman := ""
	i := 0
	
	for num > 0 {
		// calculate the number of times this num is completly divisible by values[i]
		// times will only be > 0, when num >= values[i]
		k := num / values[i]
		for j := 0; j < k; j++ {
			//buildup roman numeral
			roman += symbols[i]
			
			//reduce the value of num.
			num -= values[i]
		}
		i++
	}
	return roman
}