解法1:根据平方数的性质——连续n个奇数相加的结果一定是平方数。

如:9=1+3+5;16=1+3+5+7;
所以,不断的进行奇数相加,并判断x大小即可

public class Solution {
    public int mysqrt(int x) {
        int i=1;
        int res=-1;
        while(x>=0){
            x=x-i;
            res++;
            i=i+2;
        }
        return res;
    }
}

解法2:二分法

public class Solution {
    public int mysqrt(int x) {
        if (x<2) 
            return x;
        int left = 1;
        int right = x/2;
        int mid =1;
        while(left<=right){
            mid = (left+right)/2 ;
            if (x/mid==mid){
                return mid;
            }
            else if (x/mid<mid){
                right=mid-1;
            }
            else{
                left = mid+1;
            }
        }
        return right;
    }
}