-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPow.php
More file actions
57 lines (47 loc) · 1.09 KB
/
Pow.php
File metadata and controls
57 lines (47 loc) · 1.09 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
56
57
<?php
declare(strict_types=1);
namespace leetcode;
class Pow
{
public static function myPow(float $x, int $n): float
{
if ($n === 0) {
return 1;
}
if ($n < 0) {
[$x, $n] = [1 / $x, -$n];
}
if ($n % 2 === 0) {
$ans = self::myPow($x * $x, $n / 2);
} else {
$ans = $x * self::myPow($x * $x, intdiv($n, 2));
}
return $ans;
}
public static function myPow2(float $x, int $n): float
{
if ($n < 0) {
[$x, $n] = [1 / $x, -$n];
}
$y = 1;
while ($n) {
if ($n & 1) { // n % 2 === 1
$y *= $x;
}
$x *= $x; // x = x ^ 2
$n >>= 1; // n /= 2
}
return $y;
}
public static function myPow3(float $x, int $n): float
{
if ($n == 0) {
return 1;
}
if ($n < 0) {
return 1 / self::myPow3($x, -$n);
}
$y = self::myPow3($x, intdiv($n, 2));
return $n % 2 === 0 ? $y * $y : $y * $y * $x;
}
}