forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_69.java
33 lines (31 loc) · 939 Bytes
/
_69.java
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
package com.fishercoder.solutions;
/**
* 69. Sqrt(x)
*
* Implement int sqrt(int x).
* Compute and return the square root of x.
*/
public class _69 {
public static class Solution1 {
/**A few key points:
* 1. all variable use long type, otherwise overflow, just cast to int before returning
* 2. left start from 0, not 1
* 3. right start from x/2 + 1, not from x*/
public int mySqrt(int x) {
long left = 0;
long right = x / 2 + 1;
while (left <= right) {
long mid = left + (right - left) / 2;
long result = mid * mid;
if (result == (long) x) {
return (int) mid;
} else if (result > x) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return (int) right;
}
}
}