题解 | 平方根

平方根

https://www.nowcoder.com/practice/e821f9ce44fb4f0aafa481ad93efb6c6

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 求非负整数 n 的平方根
     * @param n int整型 你需要求 n 的平方根
     * @return double浮点型
     */
    double findSqrt(int n) {
        // write code here
        double low=0,mid,high=n;

        while(high-low>1e-5){
            mid=(low+high)/2;
            double square=mid*mid;
            if(square>n){
                high=mid;
            }else if(square<n){
                low=mid;
            }else{
                return square;
            }
        }
        return low;
        
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务