-
Notifications
You must be signed in to change notification settings - Fork 0
/
069_SqrtX69.java
65 lines (56 loc) · 1.46 KB
/
069_SqrtX69.java
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
64
65
/**
* Implement int sqrt(int x).
*
* Compute and return the square root of x.
*/
public class SqrtX69 {
public int mySqrt(int x) {
return (int)Math.sqrt(x);
}
/**
* https://discuss.leetcode.com/topic/8680/a-binary-search-solution
*/
public int mySqrt2(int x) {
if (x == 0)
return 0;
int left = 1, right = Integer.MAX_VALUE;
while (true) {
int mid = left + (right - left)/2;
if (mid > x/mid) {
right = mid - 1;
} else {
if (mid + 1 > x/(mid + 1))
return mid;
left = mid + 1;
}
}
}
/**
* https://discuss.leetcode.com/topic/24532/3-4-short-lines-integer-newton-every-language
*/
public int mySqrt3(int x) {
long r = x;
while (r*r > x)
r = (r + x/r) / 2;
return (int) r;
}
/**
* https://discuss.leetcode.com/topic/2671/share-my-o-log-n-solution-using-bit-manipulation/26
*/
public int mySqrt(int x) {
if(x==0)
return 0;
int h=0;
while((long)(1<<h)*(long)(1<<h)<=x) // firstly, find the most significant bit
h++;
h--;
int b=h-1;
int res=(1<<h);
while(b>=0){ // find the remaining bits
if((long)(res | (1<<b))*(long)(res |(1<<b))<=x)
res|=(1<<b);
b--;
}
return res;
}
}