forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sqrtx.swift
33 lines (28 loc) · 864 Bytes
/
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
/**
* Question Link: https://leetcode.com/problems/sqrtx/
* Primary idea: Binary Search, right should start with x / 2 + 1, thus its square is x + x ^ 2 / 4 + 1,
* which is definitely greater than x
*
* Note: please use (right - left) / 2 + left to get mid in case of integer overflow
*
* Time Complexity: O(logn), Space Complexity: O(1)
*/
class Sqrtx {
func mySqrt(_ x: Int) -> Int {
guard x >= 0 else {
return 0
}
var left = 0, right = x / 2 + 1
while left <= right {
let mid = (right - left) / 2 + left
if mid * mid == x {
return mid
} else if mid * mid < x {
left = mid + 1
} else {
right = mid - 1
}
}
return right
}
}