Posted on by Kalkicode
Code Conversion

Decimal to roman numeral converter in php

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

<?php 
//  Php program for
//  Conversion from Decimal to roman number
class Perform
{
    // Display roman value of n
    function result($n)
    {
        switch ($n) {
            // Test Cases
            case 1:
                echo "I";
                break;
            case 4:
                echo "IV";
                break;
            case 5:
                echo "V";
                break;
            case 9:
                echo "IX";
                break;
            case 10:
                echo "X";
                break;
            case 40:
                echo "XL";
                break;
            case 50:
                echo "L";
                break;
            case 90:
                echo "XC";
                break;
            case 100:
                echo "C";
                break;
            case 400:
                echo "CD";
                break;
            case 500:
                echo "D";
                break;
            case 900:
                echo "DM";
                break;
            case 1000:
                echo "M";
                break;
        }
    }
    function select($number, &$collection, $size)
    {
        $n = 1;
        $i = 0;
        for (
        $i = 0; $i < $size; ++$i)
        {
            if ($number >= $collection[$i])
            {
                $n = $collection[$i];
            }
            else
            {
                break;
            }
        }
        Perform::result($n);
        // Reduce the value of number
        return $number - $n;
    }
    function romanNo($number)
    {
        if ($number <= 0)
        {
            // When is not a natural number
            return;
        }
        // Base case collection
        $collection = array(
            1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
        );
        // Get the size of collection
        $size = count($collection);
        echo " " . $number . " : ";
        while ($number > 0)
        {
            $number = Perform::select($number, $collection, $size);
        }
        // Add new line
        print("\n");
    }

}
function main()
{
    // Test Case
    Perform::romanNo(10);
    Perform::romanNo(18);
    Perform::romanNo(189);
    Perform::romanNo(604);
    Perform::romanNo(982);
    Perform::romanNo(3000);
}
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