Skip to main content

Decimal to roman numeral converter in golang

Go program for Decimal to roman numeral converter. Here more solutions.

package main
import "fmt"

//  Golang program for
//  Conversion from Decimal to roman number

// Display roman value of n
func result(n  int64) {
    switch (n) {
    // Test Cases
    case 1:
        fmt.Print("I");
        break;
    case 4:
        fmt.Print("IV");
        break;
    case 5:
        fmt.Print("V");
        break;
    case 9:
        fmt.Print("IX");
        break;
    case 10:
        fmt.Print("X");
        break;
    case 40:
        fmt.Print("XL");
        break;
    case 50:
        fmt.Print("L");
        break;
    case 90:
        fmt.Print("XC");
        break;
    case 100:
        fmt.Print("C");
        break;
    case 400:
        fmt.Print("CD");
        break;
    case 500:
        fmt.Print("D");
        break;
    case 900:
        fmt.Print("DM");
        break;
    case 1000:
        fmt.Print("M");
        break;
    }
}
func selecting(number int64, collection []int64,  size  int64)int64 {
    var  n  int64 = 1;
    var  i  int64 = 0;
    for i = 0; i < size; i++ {
        if (number >= collection[i]) {
            n = collection[i];
        } else {
            break;
        }
    }
    result(n);
    // Reduce the value of number
    return number - n;
}
func romanNo(number  int64) {
    if (number <= 0) {
        // When is not a natural number
        return;
    }
    // Base case collection
    var  collection = []int64 {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000}
    // Get the size of collection
    var  size  int64 = int64(len(collection));
    fmt.Printf(" %d : ",number);
    for(number > 0) {
        number = selecting(number, collection, size);
    }
    // Add new line
    fmt.Println();
}

func main() {
    // Test Case
    romanNo(10);
    romanNo(18);
    romanNo(189);
    romanNo(604);
    romanNo(982);
    romanNo(3000);
 }

Output

 10 : X
 18 : XVIII
 189 : CLXXXIX
 604 : DCIV
 982 : DMLXXXII
 3000 : MMM




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment