We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 31aca59 commit a93039dCopy full SHA for a93039d
kotlin/0069-sqrtx.kt
@@ -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
32
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