Skip to main content

Decimal to roman numeral converter in kotlin

Kotlin program for Decimal to roman numeral converter. Here mentioned other language solution.

//  Kotlin program for
//  Conversion from Decimal to roman number
class Perform {
    // Display roman value of n
    fun show(n : Int) : Unit
    {
        when (n)
         {
            // Test Cases
            1  -> print("I");
            4  -> print("IV");
            5  -> print("V"); 
            9  -> print("IX");
            10 -> print("X");
            40 -> print("XL");
            50 -> print("L");
            90 -> print("XC");
            100-> print("C");
            400-> print("CD");
            500-> print("D");  
            900-> print("DM");
            1000-> print("M");
        }
    }
    fun select(number : Long, 
               collection : Array<Int>, 
               size : Int) : Long
    {
        var n : Int = 1;
        var i : Int = 0;
        while (i < size)
        {
            if (number >= collection[i])
            {
                n = collection[i];
            }
            else
            {
                break;
            }
            i += 1;
        }
        this.show(n);
        // Reduce the value of number
        return number - n;
    }
    fun roman(n : Long) : Unit
    {
      	var number = n;
        if (number <= 0)
        {
            // When is not a natural number
            return;
        }
        // Base case collection
        val collection : Array<Int> =
        arrayOf(1, 4, 5, 9, 10, 40, 50,
         90, 100, 400, 500, 900, 1000);
        // Get the size of collection
        val size : Int = collection.count();
        print(" " + n + " : ");
        while (number > 0)
        {
            number = this.select(number, collection, size);
        }
        println();
    }
}
fun main(args : Array<String>) : Unit
{
    val task : Perform = Perform();
    // Test Case
    task.roman(10);
    task.roman(18);
    task.roman(189);
    task.roman(604);
    task.roman(982);
    task.roman(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