File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 69. Sqrt(x)
3
+ *
4
+ * Implement int sqrt(int x).
5
+ *
6
+ * Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
7
+ *
8
+ * Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
9
+ *
10
+ * Example 1:
11
+ *
12
+ * Input: 4
13
+ * Output: 2
14
+ *
15
+ * Example 2:
16
+ *
17
+ * Input: 8
18
+ * Output: 2
19
+ * Explanation: The square root of 8 is 2.82842..., and since
20
+ * the decimal part is truncated, 2 is returned.
21
+ */
22
+
23
+ /**
24
+ * @param {number } x
25
+ * @return {number }
26
+ */
27
+ var mySqrt = function ( x ) {
28
+ if ( x < 2 ) return x ;
29
+ var left = 1 ;
30
+ var right = x ;
31
+ var mid = 0 ;
32
+ while ( left <= right ) {
33
+ mid = left + Math . floor ( ( right - left ) / 2 ) ;
34
+ if ( mid > x / mid ) {
35
+ right = mid - 1 ;
36
+ } else if ( ( mid + 1 ) > x / ( mid + 1 ) ) {
37
+ return mid ;
38
+ } else {
39
+ left = mid + 1 ;
40
+ }
41
+ }
42
+ } ;
You can’t perform that action at this time.
0 commit comments