Test Failed
Push — master ( 3b65aa...870abf )
by Jinyun
02:21
created

Pow::myPow3()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 4
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class Pow
8
{
9
    public static function myPow(float $x, int $n): float
10
    {
11
        if ($n === 0) {
12
            return 1;
13
        }
14
15
        if ($n < 0) {
16
            [$x, $n] = [1 / $x, -$n];
17
        }
18
19
        if ($n % 2 === 0) {
20
            $ans = self::myPow($x * $x, $n / 2);
21
        } else {
22
            $ans = $x * self::myPow($x * $x, intdiv($n, 2));
23
        }
24
25
        return $ans;
26
    }
27
28
    public static function myPow2(float $x, int $n): float
29
    {
30
        if ($n < 0) {
31
            [$x, $n] = [1 / $x, -$n];
32
        }
33
        $ans = 1;
34
        while ($n) {
35
            if ($n & 1) {
36
                $ans *= $x;
37
            }
38
            $x *= $x;
39
            $n >>= 1;
40
        }
41
42
        return $ans;
43
    }
44
45
    public static function myPow3(float $x, int $n): float
46
    {
47
        if ($n == 0) {
48
            return 1;
49
        }
50
        if ($n < 0) {
51
            return 1 / self::myPow3($x, -$n);
52
        }
53
        $y = self::myPow3($x, (int)($n / 2));
54
55
        return $n % 2 === 0 ? $y * $y : $y * $y * $x;
56
    }
57
}
58