-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRomeNumber.php
More file actions
74 lines (62 loc) · 1.25 KB
/
RomeNumber.php
File metadata and controls
74 lines (62 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php declare(strict_types=1);
namespace h4kuna\DataType\Number;
use Nette\StaticClass;
/**
* @example
* echo RomeNumber::getRome(1968); // MCMLXVIII
* echo RomeNumber::getArabic('MCMLXVIII'); // 1968
* @see https://php.vrana.cz/rimske-cislice.php
*/
class RomeNumber
{
use StaticClass;
private const NUMBERS = [
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1,
];
/**
* Transform from arabic to rome
*/
public static function getRome(int $number): string
{
$return = null;
foreach (self::NUMBERS as $key => $val) {
$return .= str_repeat($key, (int) floor($number / $val));
$number %= $val;
}
return $return;
}
/**
* Transform form rome to arabic
*/
public static function getArabic(string $rome): int
{
$return = 0;
$move = false;
$rome = str_split(strtoupper($rome));
foreach ($rome as $key => $val) {
if ($move === true) {
$move = false;
continue;
}
if (isset($rome[$key + 1]) && isset(self::NUMBERS[$val . $rome[$key + 1]])) {
$return += self::NUMBERS[$val . $rome[$key + 1]];
$move = true;
} else {
$return += self::NUMBERS[$val];
}
}
return $return;
}
}