CS 161 - Introduction to Programming with PHP

Solution: Assignment #4
 
<?php // Values of digits in the Roman system: // $values=array('I'=>1, 'V'=>5, 'X'=>10, 'L'=>50, 'C'=>100, 'D'=>500, 'M'=>1000); echo "Enter a Roman number: "; $roman=trim(fgets(STDIN)); $roman=strtoupper($roman); $decimal=0; $length=strlen($roman); // Number of digits in Roman number $i=0; while ($i<$length) { // While we have more digits to use... $d0=$values[$roman[$i]]; // Value of current digit if ($i+1<$length) { // Digits follow... $d1=$values[$roman[$i+1]]; if ($d1>$d0) { // Larger values mean we use the pair $d0=$d1-$d0; // Second-First $i++; // Don't use this digit again } } $decimal+=$d0; $i++; // Advance to the next digit } echo "$decimal\n"; ?>
Page last updated 17 October 2010