Implement int sqrt(int x)
.
Compute and return the square root of x.
使用牛顿迭代,详见原理http://blog.punkid.org/2008/02/28/compute-the-square-root-via-newtons-iteration/
public int sqrt(int x) {
// Start typing your Java solution below
// DO NOT write main() function
double ans = x;
while(Math.abs(ans*ans - x) > 0.0001)
{
ans = (ans+x/ans)/2;
}
return (int) ans;
}