RomanNumerals.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /*
  3. * By adding type hints and enabling strict type checking, code can become
  4. * easier to read, self-documenting and reduce the number of potential bugs.
  5. * By default, type declarations are non-strict, which means they will attempt
  6. * to change the original type to match the type specified by the
  7. * type-declaration.
  8. *
  9. * In other words, if you pass a string to a function requiring a float,
  10. * it will attempt to convert the string value to a float.
  11. *
  12. * To enable strict mode, a single declare directive must be placed at the top
  13. * of the file.
  14. * This means that the strictness of typing is configured on a per-file basis.
  15. * This directive not only affects the type declarations of parameters, but also
  16. * a function's return type.
  17. *
  18. * For more info review the Concept on strict type checking in the PHP track
  19. * <link>.
  20. *
  21. * To disable strict typing, comment out the directive below.
  22. */
  23. declare(strict_types=1);
  24. class mapping
  25. {
  26. public int $n;
  27. public string $lit;
  28. public function __construct(int $n, string $lit)
  29. {
  30. $this->n = $n;
  31. $this->lit = $lit;
  32. }
  33. }
  34. function toRoman(int $number): string
  35. {
  36. $literals = [
  37. new mapping(10_00, "M"),
  38. new mapping(9_00, "CM"),
  39. new mapping(5_00, "D"),
  40. new mapping(4_00, "CD"),
  41. new mapping(1_00, "C"),
  42. new mapping(90, "XC"),
  43. new mapping(50, "L"),
  44. new mapping(40, "XL"),
  45. new mapping(10, "X"),
  46. new mapping(9, "IX"),
  47. new mapping(5, "V"),
  48. new mapping(4, "IV"),
  49. new mapping(1, "I"),
  50. ];
  51. $roman = "";
  52. foreach ($literals as $mapping) {
  53. while ($number >= $mapping->n) {
  54. $roman .= $mapping->lit;
  55. $number -= $mapping->n;
  56. }
  57. }
  58. return $roman;
  59. }