Created
May 6, 2015 09:52
-
-
Save Doggie52/25897641799c1e364741 to your computer and use it in GitHub Desktop.
PHP: Roman numeral to int converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Takes a roman numeral input and outputs its integer value. | |
*/ | |
function roman_to_int( $in ) { | |
$out = 0; | |
$i = 0; | |
$prev_map = 0; | |
// loop through each char | |
while ( isset( $in[$i] ) ) { | |
// map our input to a number | |
switch ( $in[$i] ) { | |
case 'I': | |
$map = 1; | |
break; | |
case 'V': | |
$map = 5; | |
break; | |
case 'X': | |
$map = 10; | |
break; | |
case 'L': | |
$map = 50; | |
break; | |
case 'C': | |
$map = 100; | |
break; | |
case 'D': | |
$map = 500; | |
break; | |
case 'M': | |
$map = 1000; | |
break; | |
} | |
// add to out | |
$out += $map; | |
// is our number greater than the one we had before? | |
if ( $map > $prev_map ) { | |
// subtract out with the previous int twice | |
$out -= 2 * $prev_map; | |
} | |
// save prev map | |
$prev_map = $map; | |
// increment $i | |
$i++; | |
} | |
// return the int | |
return $out; | |
} | |
echo roman_to_int('II'); // 2 | |
echo "\n"; | |
echo roman_to_int('XX'); // 20 | |
echo "\n"; | |
echo roman_to_int('VI'); // 6 | |
echo "\n"; | |
echo roman_to_int('XI'); // 11 | |
echo "\n"; | |
echo roman_to_int('IV'); // 4 | |
echo "\n"; | |
echo roman_to_int('XIV'); // 14 | |
echo "\n"; | |
echo roman_to_int('XIX'); // 19 | |
echo "\n"; | |
echo roman_to_int('XCIX'); // 99 | |
echo "\n"; | |
echo roman_to_int('XCV'); // 95 | |
echo "\n"; | |
echo roman_to_int('DCCCXC'); // 890 | |
echo "\n"; | |
echo roman_to_int('MDCCC'); // 1800 | |
echo "\n"; | |
echo roman_to_int('I'); // 1 | |
echo "\n"; | |
echo roman_to_int('V'); // 5 | |
echo "\n"; | |
echo roman_to_int('X'); // 10 | |
echo "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment