-
Notifications
You must be signed in to change notification settings - Fork 15
/
69_Sqrtx.swift
55 lines (51 loc) · 966 Bytes
/
69_Sqrtx.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
//
// 69_Sqrtx.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-09-03.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:69 Sqrt(x)
URL: https://leetcode.com/problems/sqrtx/
Space: O(1)
Time: O(lgn)
*/
class Sqrt_Solution {
func mySqrt(_ x: Int) -> Int {
guard x > 1 else {
return x >= 0 ? x : -1
}
var start = 1
var end = x
while start + 1 < end {
let mid = start + (end - start) / 2
if mid * mid == x {
return mid
} else if mid * mid > x {
end = mid
} else {
start = mid
}
}
if start * start == x {
return start
}
if start * start < x && end * end > x {
return start
}
if end * end == x {
return end
}
return -1
}
func test() {
print(mySqrt(10))
print(mySqrt(1))
print(mySqrt(36))
print(mySqrt(0))
print(mySqrt(100))
print(mySqrt(10000))
}
}