-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13.php
More file actions
55 lines (53 loc) · 1.14 KB
/
13.php
File metadata and controls
55 lines (53 loc) · 1.14 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
<?php
class Solution
{
protected $roman = array(
"I" => 1,
"V" => 5,
"X" => 10,
"L" => 50,
"C" => 100,
"D" => 500,
"M" => 1000
);
function romanToInt($s)
{
$len = strlen($s) - 1;
if($len==0){
return $this->roman[$s[$len]];
}
$sum = 0;
$f = 1;
for ($i = 1; $i <= $len;) {
if($f==0){
$i++;
}
$prev = $this->roman[$s[$i - 1]]; //1000
if($i>$len){
$sum += $prev;
return $sum;
}
$now = $this->roman[$s[$i]]; //100
if ($prev >= $now) {
$f = 1;
$sum += $prev;
$i++;
} else {
$f = 0;
$sum += $now;
$sum -= $prev;
$i++;
}
}
// return $sum;
if ($f == 1) {
$sum += $this->roman[$s[$len]];
return $sum;
} else {
return $sum;
}
}
}
$obj = new Solution();
$s = "MCMXCIV";
echo $obj->romanToInt($s);