Posted on by Kalkicode
Code Conversion

Decimal to roman numeral converter in node js

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

//  Node Js program for
//  Conversion from Decimal to roman number
class Perform
{
    // Display roman value of n
    show(n)
    {
        switch (n) {
            // Test Cases
            case 1:
                this.ans += "I";
                break;
            case 4:
                this.ans += "IV";
                break;
            case 5:
                this.ans += "V";
                break;
            case 9:
                this.ans += "IX";
                break;
            case 10:
                this.ans += "X";
                break;
            case 40:
                this.ans += "XL";
                break;
            case 50:
                this.ans += "L";
                break;
            case 90:
                this.ans += "XC";
                break;
            case 100:
                this.ans += "C";
                break;
            case 400:
                this.ans += "CD";
                break;
            case 500:
                this.ans += "D";
                break;
            case 900:
                this.ans += "DM";
                break;
            case 1000:
                this.ans += "M";
                break;
        }
    }
    select(number, collection, size)
    {
        var n = 1;
        var i = 0;
        for (
        i = 0; i < size; ++i)
        {
            if (number >= collection[i])
            {
                n = collection[i];
            }
            else
            {
                break;
            }
        }
        this.show(n);
        // Reduce the value of number
        return number - n;
    }
    roman(number)
    {
        if (number <= 0)
        {
            // When is not a natural number
            return;
        }
        this.ans = "";
      	var num = number;
        // Base case collection
        var collection = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
        // Get the size of collection
        var size = collection.length;

        while (number > 0)
        {
            number = this.select(number, collection, size);
        }
        console.log(" " + num + " : " +this.ans);
    }
}
function main()
{
    var task = new Perform();
    // Test Case
    task.roman(10);
    task.roman(18);
    task.roman(189);
    task.roman(604);
    task.roman(982);
    task.roman(3000);
}
 // Start program execution
main();

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