Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

Β 

History

History
History
63 lines (47 loc) Β· 1.11 KB

File metadata and controls

63 lines (47 loc) Β· 1.11 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package Leetcode.Youtube;
public class SquareRootX {
public static int mySqrt(int x) {
for (int i = 0; i <= x; i++) {
if (i * i == x)
return i;
if (i * i > x) {
return i - 1;
}
}
return -1;
}
// optimal approach using binary search
public static int mySqrt2(int x) {
if (x < 2)
return x;
long low = 1, high = x / 2;
long ans = 0;
while (low <= high) {
long mid = low + (high - low) / 2;
if (mid * mid <= x) {
ans = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return (int)ans;
}
public static void main(String[] args) {
System.out.println(mySqrt(4));
System.out.println(mySqrt(8));
System.out.println(mySqrt(2));
System.out.println(mySqrt(67));
System.out.println(mySqrt(86));
System.out.println(mySqrt(40));
System.out.println(mySqrt(999999999));
System.out.println();
System.out.println(mySqrt2(4));
System.out.println(mySqrt2(8));
System.out.println(mySqrt2(2));
System.out.println(mySqrt2(67));
System.out.println(mySqrt2(86));
System.out.println(mySqrt2(40));
System.out.println(mySqrt2(999999999));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.