Skip to content

Instantly share code, notes, and snippets.

@vertexvaar
Created April 27, 2019 17:45
Show Gist options
  • Select an option

  • Save vertexvaar/dd273f1fd882e36fb03b9a7edb8a7f19 to your computer and use it in GitHub Desktop.

Select an option

Save vertexvaar/dd273f1fd882e36fb03b9a7edb8a7f19 to your computer and use it in GitHub Desktop.
Convert decimal integer to roman numerals
<?php
$input = 3486;
$expected = '';
function whatever(int $input)
{
$map = [
1 => 'I',
5 => 'V',
10 => 'X',
50 => 'L',
100 => 'C',
500 => 'D',
1000 => 'M',
];
$rules = [
[1000, 100],
[500, 100],
[100, 10],
[50, 10],
[10, 1],
[5, 1],
[1, 0],
];
$result = '';
foreach ($rules as $set) {
$upper = $set[0];
$lower = $set[1];
$upperChar = $map[$upper];
$lowerChar = $map[$lower];
$count = (int)($input / $upper);
$input -= $count * $upper;
$result .= str_repeat($upperChar, $count);
$threshold = $upper - $lower;
if ($input >= $threshold) {
$input -= $threshold;
$result .= $lowerChar . $upperChar;
}
}
return $result;
}
echo $input . ' -> ' . whatever($input);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment