题目链接:https://leetcode.com/problems/sqrtx/
思路,用牛顿迭代法,预设一个精度为 1e-6。
初始值一般习惯取1。
AC 13ms 99.5% Java:
class Solution {
public int mySqrt(int x) {
double d=1;
while(Math.abs(d*d-x)>1e-6){
d=(d+x/d)/2;
}
return (int)d;
}
}