forked from Su-Khan95/Java_Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqrt.java
More file actions
23 lines (23 loc) · 714 Bytes
/
sqrt.java
File metadata and controls
23 lines (23 loc) · 714 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.company;
//leetcode:https://leetcode.com/problems/sqrtx/
public class Sqrt {
public static void main(String[] args) {
int ans = mySqrt(81);
System.out.println(ans);
}
static int mySqrt(int x) {
if (x == 0) return 0;
int start = 1, end = x;
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid <= x / mid && (mid + 1) > x / (mid + 1))// Found the result
return mid;
else if (mid > x / mid)// Keep checking the left part
end = mid;
else {
start = mid + 1;// Keep checking the right part
}
}
return start;
}
}