forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivideTwoIntegers.swift
More file actions
30 lines (24 loc) · 844 Bytes
/
DivideTwoIntegers.swift
File metadata and controls
30 lines (24 loc) · 844 Bytes
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
/**
* Question Link: https://leetcode.com/problems/divide-two-integers/
* Primary idea: Use left shift and subtraction to get the number of every digit
* Time Complexity: O(logn), Space Complexity: O(1)
*
*/
class DivideTwoIntegers {
func divide(_ dividend: Int, _ divisor: Int) -> Int {
if divisor == 0 {
return Int.max
}
let isNegative = (dividend < 0) != (divisor < 0)
var dividend = abs(dividend), divisor = abs(divisor), count = 0
while dividend >= divisor {
var shift = 0
while dividend >= (divisor << shift) {
shift += 1
}
dividend -= divisor << (shift - 1)
count += 1 << (shift - 1)
}
return isNegative ? -count : count
}
}