Skip to content

Commit 133b8a1

Browse files
authored
[Math] Refactor solution to Divide Two Integers
1 parent 2fabc54 commit 133b8a1

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

Math/DivideTwoIntegers.swift

+19-7
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,7 @@
77

88
class DivideTwoIntegers {
99
func divide(_ dividend: Int, _ divisor: Int) -> Int {
10-
if divisor == 0 {
11-
return Int.max
12-
}
13-
14-
let isNegative = (dividend < 0) != (divisor < 0)
10+
let isPositive = (dividend < 0) == (divisor < 0)
1511
var dividend = abs(dividend), divisor = abs(divisor), count = 0
1612

1713
while dividend >= divisor {
@@ -22,9 +18,25 @@
2218
}
2319

2420
dividend -= divisor << (shift - 1)
25-
count += 1 << (shift - 1)
21+
22+
count += (1 << (shift - 1))
23+
}
24+
25+
return refactorCount(count, isPositive)
26+
}
27+
28+
private func refactorCount(_ count: Int, _ isPositive: Bool) -> Int {
29+
let INTMAX = 2147483647
30+
var count = count
31+
32+
if isPositive {
33+
if count > INTMAX {
34+
count = INTMAX
35+
}
36+
} else {
37+
count *= -1
2638
}
2739

28-
return isNegative ? -count : count
40+
return count
2941
}
3042
}

0 commit comments

Comments
 (0)