Created
April 27, 2019 17:45
-
-
Save vertexvaar/dd273f1fd882e36fb03b9a7edb8a7f19 to your computer and use it in GitHub Desktop.
Convert decimal integer to roman numerals
This file contains hidden or 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 | |
| $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