Skip to content

Commit a96c958

Browse files
authored
[Search] Refactor solution to Sqrt(x)
1 parent 313a70f commit a96c958

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

Search/Sqrtx.swift

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,15 @@
99
*/
1010

1111
class Sqrtx {
12-
func mySqrt(x: Int) -> Int {
13-
if x <= 0 {
14-
return x
12+
func mySqrt(_ x: Int) -> Int {
13+
guard x >= 0 else {
14+
return 0
1515
}
1616

17-
var left = 0
18-
var right = x / 2 + 1
19-
var mid = 0
20-
17+
var left = 0, right = x / 2 + 1
18+
2119
while left <= right {
22-
mid = (right - left) / 2 + left
20+
let mid = (right - left) / 2 + left
2321

2422
if mid * mid == x {
2523
return mid
@@ -32,4 +30,4 @@ class Sqrtx {
3230

3331
return right
3432
}
35-
}
33+
}

0 commit comments

Comments
 (0)