Skip to content

Commit a2b0cb8

Browse files
committed
Add divide-two-integers solution
1 parent 213ce8a commit a2b0cb8

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

src/leetcode/DivideTwoIntegers.php

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode\tests;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use leetcode\DivideTwoIntegers;
9+
10+
class DivideTwoIntegersTest extends TestCase
11+
{
12+
public function testDivide(): void
13+
{
14+
self::assertSame(3, DivideTwoIntegers::divide(10, 3));
15+
self::assertSame(-2, DivideTwoIntegers::divide(7, -3));
16+
self::assertSame(0, DivideTwoIntegers::divide(0, 1));
17+
self::assertSame(1, DivideTwoIntegers::divide(1, 1));
18+
self::assertSame(715827882, DivideTwoIntegers::divide(-2147483648, -3));
19+
}
20+
21+
public function testDivide2(): void
22+
{
23+
self::assertSame(3, DivideTwoIntegers::divide2(10, 3));
24+
self::assertSame(-2, DivideTwoIntegers::divide2(7, -3));
25+
self::assertSame(0, DivideTwoIntegers::divide2(0, 1));
26+
self::assertSame(1, DivideTwoIntegers::divide2(1, 1));
27+
self::assertSame(715827882, DivideTwoIntegers::divide2(-2147483648, -3));
28+
}
29+
}

0 commit comments

Comments
 (0)