Go Program: Convert Numbers to Roman Numerals and Vice Versa

This Go program provides functions to convert numbers to Roman numerals and vice versa. The structure of the program is divided into two main functions: toRoman and fromRoman. The first function converts an integer to a Roman numeral string, and the second function converts a Roman numeral string back to an integer.

Program Structure

The program is structured as follows:

  • toRoman: Converts an integer to a Roman numeral.
  • fromRoman: Converts a Roman numeral to an integer.

Code Implementation


// Package main contains the main function to run the program.
package main

import (
    "fmt"
    "strings"
)

// A map of integer values to Roman numeral symbols.
var romanNumerals = []struct {
    Value 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"},
}

// toRoman converts an integer to a Roman numeral string.
func toRoman(num int) string {
    var result strings.Builder
    for _, numeral := range romanNumerals {
        for num >= numeral.Value {
            result.WriteString(numeral.Symbol)
            num -= numeral.Value
        }
    }
    return result.String()
}

// fromRoman converts a Roman numeral string to an integer.
func fromRoman(roman string) int {
    var result int
    i := 0
    for i < len(roman) {
        if i+1 < len(roman) {
            twoChar := roman[i : i+2]
            oneChar := roman[i : i+1]
            found := false
            for _, numeral := range romanNumerals {
                if twoChar == numeral.Symbol {
                    result += numeral.Value
                    i += 2
                    found = true
                    break
                } else if oneChar == numeral.Symbol {
                    result += numeral.Value
                    i++
                    found = true
                    break
                }
            }
            if !found {
                i++
            }
        } else {
            oneChar := roman[i : i+1]
            for _, numeral := range romanNumerals {
                if oneChar == numeral.Symbol {
                    result += numeral.Value
                    break
                }
            }
            i++
        }
    }
    return result
}

// main is the entry point of the program.
func main() {
    // Test the toRoman function.
    num := 1987
    roman := toRoman(num)
    fmt.Printf("%d in Roman numerals is %s\n", num, roman)
    
    // Test the fromRoman function.
    romanStr := "MCMLXXXVII"
    number := fromRoman(romanStr)
    fmt.Printf("%s in integer is %d\n", romanStr, number)
}

Explanation

The program starts with importing the necessary packages: fmt for formatted I/O and strings for string manipulation. The romanNumerals slice contains the Roman numeral symbols and their corresponding integer values.

toRoman Function

This function takes an integer as input and converts it to a Roman numeral string:

  • It iterates over the romanNumerals slice.
  • For each symbol, it appends the symbol to the result while subtracting the symbol’s value from the input number until the input number is less than the symbol’s value.
  • The final result is the Roman numeral string representation of the input number.

fromRoman Function

This function takes a Roman numeral string as input and converts it to an integer:

  • It iterates over the input string, checking for two-character symbols first and then one-character symbols.
  • If a match is found, the corresponding value is added to the result and the index is incremented accordingly.
  • The final result is the integer representation of the input Roman numeral string.

Testing the Functions

The main function tests both toRoman and fromRoman functions with sample inputs to demonstrate their usage.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)