-
Notifications
You must be signed in to change notification settings - Fork 0
/
13RomanToInt.php
55 lines (44 loc) · 1.11 KB
/
13RomanToInt.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
49
50
51
52
53
54
55
<?php declare(strict_types = 1);
final class Solution
{
private const ROMAN_NUMBERS = [
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
];
public function romanToInt(string $s): int
{
$result = 0;
$previousNumber = 0;
$len = strlen($s);
$rev = strrev($s);
for ($i = 0; $i < $len; $i++) {
$romanNumber = $rev[$i];
$number = self::ROMAN_NUMBERS[$romanNumber];
if ($number >= $previousNumber) {
$result += $number;
} else {
$result -= $number;
}
$previousNumber = $number;
}
return $result;
}
}
/* Client code below */
$solution = new Solution();
$testCases = [
'III' => 3,
'IV' => 4,
'MC' => 1100,
'MMXXII' => 2022,
'MCMXXII' => 1922,
];
foreach ($testCases as $romanNumber => $expectedNumber) {
$result = $solution->romanToInt($romanNumber);
assert($expectedNumber === $result, "$romanNumber == $expectedNumber not $result");
}