leetcode 69.x的平方根(Java 二分查找 easy)

https://leetcode-cn.com/problems/sqrtx/

实现int sqrt(int x)函数,给定一个数字,求sqrt(x)并且保留整数部分。

二分查找,令l=1,h=x,判断l<=h,当跳出循环时,即sqrt(x)不为整数时,return h,因为跳出循环时l>h,本题要求只保留整数部分,不四舍五入。

class Solution {
    public int mySqrt(int x) {
        if(x<=1) return x;
        int l=1,h=x;
        while(l<=h){
            int mid=l+(h-l)/2;
            int sqrt=x/mid;
            if(sqrt==mid){
                return mid;
            }
            else if(sqrt<mid){
                h=mid-1;
            }
            else{
                l=mid+1;
            }
        }
        return h;
    }
}

猜你喜欢

转载自www.cnblogs.com/y1040511302/p/11569004.html