Last active
December 29, 2017 13:17
-
-
Save rimas-kudelis/07b19a37fea41186e9331651b15dd381 to your computer and use it in GitHub Desktop.
Arabic to Roman numerals 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 | |
namespace App; | |
/** | |
* Converts positive decimal numbers to Roman numerals. | |
* Note: M (1000) is the largest Roman numeral supported by this function. | |
*/ | |
class Converter | |
{ | |
protected $mappings = [ | |
[ 'I', 'V', 'X' ], | |
[ 'X', 'L', 'C' ], | |
[ 'C', 'D', 'M' ], | |
//[ 'M', 'ↁ', 'ↂ'], | |
]; | |
function digit($num, $mapping) | |
{ | |
if ($num <= 3) { | |
return str_repeat($mapping[0], $num); | |
} | |
if ($num == 4) { | |
return $mapping[0] . $mapping[1]; | |
} | |
if ($num <= 8) { | |
return $mapping[1] . str_repeat($mapping[0], $num - 5); | |
} | |
// if $num === 9 | |
return $mapping[0] . $mapping[2]; | |
} | |
function convert($number) { | |
$numString = "$number"; | |
$roman = ''; | |
$mappings = $this->mappings; | |
while(strlen($numString) > 0 && !empty($mappings)) { | |
$digit = substr($numString, -1); | |
$numString = substr($numString, 0, -1); | |
$currentMapping = array_shift($mappings); | |
$roman = $this->digit((int)$digit, $currentMapping) . $roman; | |
} | |
$roman = str_repeat($currentMapping[2], (int)$numString) . $roman; | |
return $roman; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment