Sqrt(x)
Total Accepted: 7788 Total Submissions: 36159Implement int sqrt(int x)
.
Compute and return the square root of x.
Some one suggest using binary search, However a Newton method seems more efficient,
With help form :
http://www.2cto.com/kf/201206/137256.html
public class Solution {
public int sqrt(int x) {
double val = x;
double last = val/2;
if(x == 0 || x<0){
return x;
}
else{
while(Math.abs(last-val)>0.000001){
last = val;
val = (val+x/val)/2;
}
}
return (int)val;
}
}