In: Computer Science
Using PHP, design a function that given a Roman numeral (Links to an external site.)Links to an external site. in input, is able to compute the modern Hindu–Arabic numeral (Links to an external site.)Links to an external site. system representation (aka, 0123456789).
For example:
Input | Output |
VI | 6 |
IV | 4 |
MCMXC | 1990 |
IX | 9 |
here i have create two function and create Roman numeral to modern Hindu–Arabic numeral
Code Roman_Numeral.php:
<?php
//Roman_symbol_value function returns roman symbol value
function Roman_symbol_value($no)
{
if ($no == 'I')
return 1;
if ($no == 'V')
return 5;
if ($no == 'X')
return 10;
if ($no == 'L')
return 50;
if ($no == 'C')
return 100;
if ($no == 'D')
return 500;
if ($no == 'M')
return 1000;
return -1;
}
//Roman_numeral function it is a given roman numeral
function Roman_numeral(&$string_value)
{
//asign result value zero
$result = 0;
//loop continues until string_value
length
for ($i = 0; $i < strlen($string_value); $i++)
{
//get value of s[i] and store in a1
$a1 = Roman_symbol_value($string_value[$i]);
if ($i+1 < strlen($string_value))
{
//get value of s[i] and store in a2
$a2 = Roman_symbol_value($string_value[$i + 1]);
// compare a1 and a2
if ($a1 >= $a2)
{
$result = $result + $a1; //store value in result
}
else
{
$result = $result + $a2 - $a1;
$i++;
}
}
else
{
$result = $result + $a1;
$i++;
}
}
return $result;
}
//basic inputs
$str ="VI";
$str1="IV";
$str2 ="MCMXC";
$str3="IX";
//basic output in table format with function call
Roman_numeral
echo "<table border=1><caption>Roman
Numeral</caption><tr><th>Input</th><th>Output</th></tr>",
"<tr><td>",$str,"</td>","<td>",Roman_numeral($str),"</td></tr>",
"<tr><td>",$str1,"</td>","<td>",Roman_numeral($str1),"</td></tr>",
"<tr><td>",$str2,"</td>","<td>",Roman_numeral($str2),"</td></tr>",
"<tr><td>",$str3,"</td>","<td>",Roman_numeral($str3),"</td></tr>";
?>
Output:
Thank you if you have any query regarding above answer please ask me in comment box.
if you like my work appreciate with thumbs up.
Thank You.