Test Failed
Push — master ( ddf58a...28c77f )
by Jinyun
02:16
created

EvaluateReversePolishNotation   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 14
eloc 35
c 1
b 0
f 0
dl 0
loc 51
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B evalRPN() 0 23 7
B evalRPN2() 0 24 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class EvaluateReversePolishNotation
8
{
9
    public static function evalRPN(array $tokens): int
10
    {
11
        if (empty($tokens)) {
12
            return 0;
13
        }
14
        $stack = new \SplStack();
15
        foreach ($tokens as $token) {
16
            if ($token === "+") {
17
                $stack->push($stack->pop() + $stack->pop());
18
            } elseif ($token === "-") {
19
                [$b, $a] = [$stack->pop(), $stack->pop()];
20
                $stack->push($a - $b);
21
            } elseif ($token === '*') {
22
                $stack->push($stack->pop() * $stack->pop());
23
            } elseif ($token === '/') {
24
                [$b, $a] = [$stack->pop(), $stack->pop()];
25
                $stack->push((int)($a / $b));
26
            } else {
27
                $stack->push((int)$token);
28
            }
29
        }
30
31
        return $stack->pop();
32
    }
33
34
    public static function evalRPN2(array $tokens): int
35
    {
36
        if (empty($tokens)) {
37
            return 0;
38
        }
39
        $stack = [];
40
        foreach ($tokens as $token) {
41
            if (!in_array($token, ['+', '-', '*', '/'])) {
42
                array_push($stack, (int)$token);
43
            } else {
44
                [$r, $l] = [array_pop($stack), array_pop($stack)];
45
                if ($token === '+') {
46
                    array_push($stack, $l + $r);
47
                } elseif ($token === '-') {
48
                    array_push($stack, $l - $r);
49
                } elseif ($token === '*') {
50
                    array_push($stack, $l * $r);
51
                } else {
52
                    array_push($stack, (int)($l / $r));
53
                }
54
            }
55
        }
56
57
        return array_pop($stack);
58
    }
59
}
60