-
Notifications
You must be signed in to change notification settings - Fork 10
/
Contents.swift
64 lines (56 loc) · 1.76 KB
/
Contents.swift
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/// 29. Divide Two Integers
/// Given two integers dividend and divisor, divide two integers without using multiplication,
/// division and mod operator. Return the quotient after dividing dividend by divisor.
///
/// - Note:
/// The integer division should truncate toward zero.
/// Both dividend and divisor will be 32-bit signed integers.
/// The divisor will never be 0.
/// Assume we are dealing with an environment which could only store integers within the 32-bit
/// signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your
/// function returns 231 − 1 when the division result overflows.
import XCTest
/// Approach: Bitwise Operation
func divide(_ dividend: Int, _ divisor: Int) -> Int {
var positive = true
var dividend = dividend
var divisor = divisor
if dividend > 0 {
dividend = ~dividend + 1
} else {
positive = !positive
}
if divisor > 0 {
divisor = ~divisor + 1
} else {
positive = !positive
}
var result = 0
while dividend <= divisor {
var temp = divisor
var base = -1
while temp << 1 >= dividend && temp << 1 < temp {
temp <<= 1
base <<= 1
}
dividend -= temp
result += base
}
if positive {
guard result != Int32.min else { return Int(Int32.max) }
result = ~result + 1
}
return result
}
class Tests: XCTestCase {
func testExample1() {
XCTAssertEqual(divide(10, 3), 3)
}
func testExample2() {
XCTAssertEqual(divide(Int(Int32.min), 1), Int(Int32.min))
}
func testExample3() {
XCTAssertEqual(divide(Int(Int32.min), -1), Int(Int32.max))
}
}
Tests.defaultTestSuite.run()