x 的平方根 (Sqrt(x))

 

思路:

// @Title: x 的平方根  (Sqrt(x))
// @Author: qisiii
// @Date: 2024-06-03 12:15:04
// @Runtime: 1 ms
// @Memory: 39.7 MB
// @comment: 
// @flag: 
class Solution {
    public int mySqrt(int x) {
        if(x==1){
            return 1;
        }
        double left=0;
        double right=x;
        while(left<right-0.001){
            double mid=left+(right-left)/2;
            if(mid*mid==x){
                return (int)mid;
            }else if(mid*mid>x){
                right=mid;
            }else{
                left=mid;
            }
        }
        int temp=(int) right;
        if(temp*temp>x){
            return (int)left;
        }
        return (int) right;
    }
}

思路:

// @Title: x 的平方根  (Sqrt(x))
// @Author: qisiii
// @Date: 2024-09-06 17:16:04
// @Runtime: 1 ms
// @Memory: 40.1 MB
// @comment: 
// @flag: 
class Solution {
    public int mySqrt(int x) {
        int left=1,right=x;
        while(left<=right){
            int mid=left+(right-left)/2;
            long sum=(long)mid*mid;
            if(sum==x){
                return mid;
            }else if(sum>x){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
        return right;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18