-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0069-sqrtx.java
More file actions
29 lines (24 loc) · 761 Bytes
/
0069-sqrtx.java
File metadata and controls
29 lines (24 loc) · 761 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
class Solution {
public int mySqrt(int x) {
// Linear search way -> loop through for all nums till x
// then see if their square <= x
// Binary Search way -> we can optimise our approach by observing
// that nums till x are sorted
int left = 0;
int right = x;
int mid = 0;
int probableAns = 0;
while(left <= right){
mid = left + (right-left)/2;
if((long)mid*mid <= (long)x){
probableAns = mid;
// let's see if we can find a bigger num
left = mid+1;
}
else if((long)mid*mid > (long)x){
right = mid-1;
}
}
return probableAns;
}
}