-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy path069Sqrt.java
More file actions
42 lines (36 loc) · 909 Bytes
/
069Sqrt.java
File metadata and controls
42 lines (36 loc) · 909 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
41
42
// Author: Li Long, [email protected]
// Date: Apr 17, 2014
// Source: http://oj.leetcode.com/problems/sqrtx/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/20002071
// Implement int sqrt(int x).
// Compute and return the square root of x.
public class Sqrt {
public int sqrt(int x) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
if (x < 2) {
return x;
}
int low = 1;
int high = x / 2;
int mid = 0;
int lastMid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (x / mid > mid) {
low = mid + 1;
lastMid = mid;
} else if (x / mid < mid) {
high = mid - 1;
} else {
return mid;
}
}
return lastMid;
}
public static void main(String[] args) {
Sqrt slt = new Sqrt();
int result = slt.sqrt(4);
System.out.println(result);
}
}