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

DivideTwoIntegers::divide()   B

Complexity

Conditions 10
Paths 16

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 32
rs 7.6666
cc 10
nc 16
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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