Test Failed
Push — master ( 213ce8...853c98 )
by Jinyun
02:16
created

DivideTwoIntegers   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 16
eloc 34
c 1
b 0
f 0
dl 0
loc 54
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A divide2() 0 18 6
B divide() 0 32 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class DivideTwoIntegers
8
{
9
    public static function divide(int $x, int $y): int
10
    {
11
        [$max, $min] = [2147483647, -2147483648];
12
        if ($x === $y) {
13
            return 1;
14
        }
15
        if ($y === 1) {
16
            return $x;
17
        }
18
        if ($x === 0) {
19
            return 0;
20
        }
21
        if ($x === $min && $y === -1) {
22
            return $max;
23
        }
24
25
        $sign = $x > 0 ^ $y > 0 ? -1 : 1;
26
        [$n, $x, $y] = [0, abs($x), abs($y)];
27
        while ($x >= $y) {
28
            [$t, $i] = [$y, 1];
29
            while ($x >= $t) {
30
                $x -= $t;
31
                $n += $i;
32
                $i <<= 1;
33
                $t <<= 1;
34
            }
35
        }
36
        if ($sign < 0) {
37
            $n = -$n;
38
        }
39
40
        return min(max($min, $n), $max);
41
    }
42
43
    public static function divide2(int $x, int $y): int
44
    {
45
        if ($x === (1 << 31) && $y === -1) {
46
            return (1 << 31) - 1;
47
        }
48
        $n = 0;
49
        [$a, $b] = [abs($x), abs($y)];
50
        while ($a - $b >= 0) {
51
            [$t, $i] = [$b, 1];
52
            while ($a - ($t << 1) >= 0) {
53
                $t <<= 1;
54
                $i <<= 1;
55
            }
56
            $a -= $t;
57
            $n += $i;
58
        }
59
60
        return ($x > 0) === ($y > 0) ? $n : -$n;
61
    }
62
}
63