int sqrt(int x)
.Compute and return the square root of x.
public class Solution {
public int sqrt(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x<0) return -1;
if(x==0) return 0;
double y = ((double)x)/2.;
while(Math.abs(y*y-x)>0.00001){
y=(y+x/y)/2.;
}
return (int) y;
}
}
=========
public class Solution {
public int mySqrt(int x) {
assert(x >= 0);
if (x <= 1) {
return x;
}
int s = 1;
int e = x;
while (s <= e) {
int m = (s + e) / 2;
if (x / m >= m && x / (m + 1) < (m + 1)) {
return m;
} else if (x / m > m) {
s = m + 1;
} else {
e = m - 1;
}
}
return 1;
}
}
=========
public class Solution {
public int mySqrt(int x) {
if (x == 0) {
return 0;
} else if (x == 1) {
return 1;
}
int s = 1, e = x / 2;
int res = 0;
while (s <= e) {
int m = s + (e - s) / 2;
if (m <= x / m) {
s = m + 1;
res = m;
} else {
e = m - 1;
}
}
return res;
}
}
没有评论:
发表评论