Skip to content

Commit 644bd62

Browse files
authored
Create 0069-sqrtx.java
Language used : java Runtime : 1ms, faster than 100% Submission : https://leetcode.com/problems/sqrtx/submissions/999842542/
1 parent ae3f8ec commit 644bd62

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Diff for: java/0069-sqrtx.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public int mySqrt(int x) {
3+
4+
// Linear search way -> loop through for all nums till x
5+
// then see if their square <= x
6+
7+
// Binary Search way -> we can optimise our approach by observing
8+
// that nums till x are sorted
9+
10+
int left = 0;
11+
int right = x;
12+
int mid = 0;
13+
int probableAns = 0;
14+
15+
while(left <= right){
16+
mid = left + (right-left)/2;
17+
if((long)mid*mid <= (long)x){
18+
probableAns = mid;
19+
// let's see if we can find a bigger num
20+
left = mid+1;
21+
}
22+
else if((long)mid*mid > (long)x){
23+
right = mid-1;
24+
}
25+
}
26+
27+
return probableAns;
28+
}
29+
}

0 commit comments

Comments
 (0)