-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathEvaluateReversePolishNotation.php
59 lines (53 loc) · 1.67 KB
/
EvaluateReversePolishNotation.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
<?php
declare(strict_types=1);
namespace leetcode;
class EvaluateReversePolishNotation
{
public static function evalRPN(array $tokens): int
{
if (empty($tokens)) {
return 0;
}
$stack = new \SplStack();
foreach ($tokens as $token) {
if ($token === "+") {
$stack->push($stack->pop() + $stack->pop());
} elseif ($token === "-") {
[$b, $a] = [$stack->pop(), $stack->pop()];
$stack->push($a - $b);
} elseif ($token === '*') {
$stack->push($stack->pop() * $stack->pop());
} elseif ($token === '/') {
[$b, $a] = [$stack->pop(), $stack->pop()];
$stack->push((int)($a / $b));
} else {
$stack->push((int)$token);
}
}
return $stack->pop();
}
public static function evalRPN2(array $tokens): int
{
if (empty($tokens)) {
return 0;
}
$stack = [];
foreach ($tokens as $token) {
if (!in_array($token, ['+', '-', '*', '/'])) {
array_push($stack, (int)$token);
} else {
[$r, $l] = [array_pop($stack), array_pop($stack)];
if ($token === '+') {
array_push($stack, $l + $r);
} elseif ($token === '-') {
array_push($stack, $l - $r);
} elseif ($token === '*') {
array_push($stack, $l * $r);
} else {
array_push($stack, (int)($l / $r));
}
}
}
return array_pop($stack);
}
}