Skip to content

Commit a93039d

Browse files
authored
Create 0069-sqrtx.kt
1 parent 31aca59 commit a93039d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

kotlin/0069-sqrtx.kt

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* Binary Search
3+
*/
4+
class Solution {
5+
fun mySqrt(x: Int): Int {
6+
var left = 0L
7+
var right = x.toLong()
8+
var res = 0L
9+
10+
while (left <= right) {
11+
val mid = left + (right - left) / 2
12+
val midSq = mid * mid
13+
14+
if (midSq > x) {
15+
right = mid - 1
16+
} else if (midSq < x) {
17+
left = mid + 1
18+
res = mid
19+
} else {
20+
return mid.toInt()
21+
}
22+
}
23+
24+
return res.toInt()
25+
}
26+
}
27+
28+
/*
29+
* Newton's method
30+
*/
31+
class Solution {
32+
fun mySqrt(x: Int): Int {
33+
if (x == 0) return 0
34+
35+
var i = x.toLong()
36+
while (i > x / i) {
37+
i = (i + x / i) / 2
38+
}
39+
40+
return i.toInt()
41+
}
42+
}

0 commit comments

Comments
 (0)