In: Computer Science
Using PHP, design a function that given a Roman numeral (Wikipedia link.), in input, is able to compute the modern Hindu–Arabic numeral (wikipedia link), system representation (aka, 0123456789).
For example:
Input | Output |
VI | 6 |
IV | 4 |
MCMXC | 1990 |
IX | 9 |
romantonumber.php:
<!DOCTYPE html>
<html>
<head>
<title>Roman to Hindu-Arabic
Number</title>
<style>
table{
width:50%;
border-collapse:collapse;
text-align:center;
}
</style>
</head>
<body>
<center>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" id="roman_input" name="roman_input"
placeholder="Enter Roman Number">
<input type="submit" value="Convert"/>
</form>
<br/>
<?php
$roman_numbers = array('M' => 1000,'CM' => 900,'D' =>
500,'CD' => 400,'C' => 100,'XC' => 90,'L' => 50,'XL'
=> 40,'X' => 10,'IX' => 9,'V' => 5,'IV' => 4,'I'
=> 1);
if(!isset($_POST['roman_input']))
return 0;
else{
$roman_input = strtoupper($_POST['roman_input']);
$output = 0;
foreach ($roman_numbers as $key => $value) {
while (strpos($roman_input, $key) === 0) {
$output += $value;
$roman_input = substr($roman_input, strlen($key));
}
}
//output
echo "<table border='1'>";
echo
"<tr><th>Input</th><th>Output</th></tr>";
echo
"<tr><td>".strtoupper($_POST['roman_input'])."</td><td>".$output."</td></tr>";
echo "</table>";
}
?>
</center>
</body>
</html>
Output Screenshots: