We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent ae3f8ec commit 644bd62Copy full SHA for 644bd62
java/0069-sqrtx.java
@@ -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