-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ12_Integer_to_Roman_Test.php
118 lines (101 loc) · 2.73 KB
/
Q12_Integer_to_Roman_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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
/**
* Date: 2019/8/7
* Time: 下午 12:12
*/
use PHPUnit\Framework\TestCase;
class Q12_Integer_to_Roman_Test extends TestCase
{
/**
* @param Integer $num
* @return String
*/
function intToRoman($num) {
$roman = [
[
"num" => 1000,
"letter" => "M",
"div" => 900,
"div_letter" => "C",
],
[
"num" => 500,
"letter" => "D",
"div" => 400,
"div_letter" => "C",
],
[
"num" => 100,
"letter" => "C",
"div" => 90,
"div_letter" => "X",
],
[
"num" => 50,
"letter" => "L",
"div" => 40,
"div_letter" => "X",
],
[
"num" => 10,
"letter" => "X",
"div" => 9,
"div_letter" => "I",
],
[
"num" => 5,
"letter" => "V",
"div" => 4,
"div_letter" => "I",
],
[
"num" => 1,
"letter" => "I",
],
];
$str = "";
$cursor = 0;
$cursorMax = sizeof($roman) ;
while ($num > 0 && $cursor < $cursorMax) {
if ($num >= $roman[$cursor]["num"]) {
if ($cursor > 0 && $num >= $roman[$cursor - 1]["div"]
&& $num < $roman[$cursor - 1]["num"]) {
$num -= $roman[$cursor - 1]["div"];
$str .= $roman[$cursor - 1]["div_letter"]
. $roman[$cursor - 1]["letter"];
} else {
$num -= $roman[$cursor]["num"];
$str .= $roman[$cursor]["letter"];
}
} else {
$cursor++;
}
}
return $str;
}
public function testOne()
{
$result = $this->intToRoman(4);
self::assertEquals("IV",$result);
}
public function testTwo()
{
$result = $this->intToRoman(3);
self::assertEquals("III",$result);
}
public function testThree()
{
$result = $this->intToRoman(58);
self::assertEquals("LVIII",$result);
}
public function testFour()
{
$result = $this->intToRoman(1994);
self::assertEquals("MCMXCIV",$result);
}
public function testFive()
{
$result = $this->intToRoman(5);
self::assertEquals("V",$result);
}
}