Created
July 16, 2017 18:06
-
-
Save MohammedAttya2/24b2130e40225929e3f229e251112bc5 to your computer and use it in GitHub Desktop.
Convert numbers to Roman Numbers
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 | |
/** | |
* Mohammed Attya | |
* RomanNumeralConverter | |
* MIT Licence | |
* run using WAMP / XAMPP / LAMP / MAMP or just php RomanNumeralConverter.php in terminal | |
* make sure to install php first | |
*/ | |
class RomanNumeralConverter | |
{ | |
private static $lookup = [ | |
1000 => 'M', | |
900 => 'CM', | |
500 => 'D', | |
400 => 'CM', | |
100 => 'C', | |
90 => 'XC', | |
50 => 'L', | |
40 => 'XL', | |
10 => 'X', | |
9 => 'IX', | |
5 => 'V', | |
4 => 'IV', | |
1 => 'I' | |
]; | |
public function convert($number) | |
{ | |
$solution = ''; | |
foreach (static::$lookup as $limit => $glyph) { | |
while ($number >= $limit) { | |
$solution .= $glyph; | |
$number -= $limit; | |
} | |
} | |
return $solution; | |
} | |
} | |
$converter = new RomanNumeralConverter; | |
// it is simple | |
// to print a list of roman numbers and arabic numbers just edit the variable n | |
$n = 100 // to make a list of first 100 numbers | |
for ($i=1; $i <= $n; $i++) { | |
echo "{$converter->convert($i)} \t is \t {$i}\n"; | |
} | |
// to convert specific number uncomment next line and edit the number | |
// echo "{$converter->convert(100)} \t is \t 100\n"; | |
// uncomment is just remove the first // |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment