-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ13_Roman_to_Integer_Test.php
87 lines (67 loc) · 1.71 KB
/
Q13_Roman_to_Integer_Test.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
* Date: 2019/8/7
* Time: 下午 12:12
*/
use PHPUnit\Framework\TestCase;
class Q13_Roman_to_Integer_Test extends TestCase
{
/**
* @param String $s
* @return Integer
*/
function romanToInt($s)
{
$roman = [
"I" => 1,
"V" => 5,
"X" => 10,
"L" => 50,
"C" => 100,
"D" => 500,
"M" => 1000,
];
$n = str_split($s);
$max = count($n);
$sum = 0;
for ($i = 0; $i < $max; $i++) {
$word = $n[$i];
$num = $roman[$word];
if ($i != $max - 1) {
if ($n[$i] == "I" && ($n[$i + 1] == "V" || $n[$i + 1] == "X")) {
$num = 0 - $roman[$word];
} elseif ($n[$i] == "X"
&& ($n[$i + 1] == "L"
|| $n[$i + 1] == "C")) {
$num = 0 - $roman[$word];
} elseif ($n[$i] == "C"
&& ($n[$i + 1] == "D"
|| $n[$i + 1] == "M")) {
$num = 0 - $roman[$word];
}
}
$sum += $num;
}
return ($sum);
}
public function testOne()
{
$result = $this->romanToInt("III");
self::assertEquals(3, $result);
}
public function testTwo()
{
$result = $this->romanToInt("IV");
self::assertEquals(4, $result);
}
public function testThree()
{
$result = $this->romanToInt("IX");
self::assertEquals(9, $result);
}
public function testFour()
{
$result = $this->romanToInt("LVIII");
self::assertEquals(58, $result);
}
}