-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq069_Sqrt.java
More file actions
40 lines (35 loc) · 915 Bytes
/
q069_Sqrt.java
File metadata and controls
40 lines (35 loc) · 915 Bytes
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
34
35
36
37
38
39
40
package leetcode_algorithm;
/**
* Implement int sqrt(int x).
* <p>
* Compute and return the square root of x.
* <p>
* Subscribe to see which companies asked this question.
*/
public class q069_Sqrt {
public static void main(String[] args) {
System.out.println(new q069_Sqrt().mySqrt(4));
System.out.println(new q069_Sqrt().mySqrt(5));
System.out.println(new q069_Sqrt().mySqrt(100000));
}
/**
* ½â·¨1
* @param x
* @return
*/
public int mySqrt(int x) {
if (x == 0)
return 0;
int left = 1, right = Integer.MAX_VALUE;
while (true) {
int mid = left + (right - left) / 2;
if (mid > x / mid) {
right = mid - 1;
} else {
if (mid + 1 > x / (mid + 1))
return mid;
left = mid + 1;
}
}
}
}