-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquareRoot.java
More file actions
38 lines (28 loc) · 865 Bytes
/
Copy pathSquareRoot.java
File metadata and controls
38 lines (28 loc) · 865 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
package LeetcodePractice;
public class SquareRoot {
public static int mySqrt(int x) {
if (x == 0 || x == 1) {
return x;
}
int left = 1, right = x;
int result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid <= x / mid) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
public static void main(String[] args) {
int x1 = 4;
System.out.println("Square root of " + x1 + " is: " + mySqrt(x1));
int x2 = 8;
System.out.println("Square root of " + x2 + " is: " + mySqrt(x2));
int x3 = 2147395600;
System.out.println("Square root of " + x3 + " is: " + mySqrt(x3));
}
}