-
Notifications
You must be signed in to change notification settings - Fork 0
/
roman-to-integer.php
48 lines (44 loc) · 995 Bytes
/
roman-to-integer.php
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
<?php
/**
* @link https://leetcode.com/problems/roman-to-integer
* @difficulty EASY
*/
class Solution
{
/**
* @var array|int[]
*/
protected array $romans = [
'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,
];
/**
* @param string $roman
* @return int
*/
public function romanToInt(string $roman) : int
{
$numeric = 0;
$length = strlen($roman);
for ($i = 0; $i < $length; $i++) {
if ($i + 1 < $length && isset($this->romans[$roman[$i] . $roman[$i + 1]])) {
$numeric += $this->romans[$roman[$i] . $roman[$i + 1]];
$i++;
} else {
$numeric += $this->romans[$roman[$i]];
}
}
return $numeric;
}
}