LeetCode69. Sqrt(x)

本文介绍了解决LeetCode上的69.Sqrt(x)问题的两种方法:一种是使用折半查找的方式,另一种是采用牛顿迭代法。这两种方法都能有效地找到指定整数的平方根。

69.Sqrt(x)

题意: 实现 int sqrt(int x), 返回根号下x。

Implement int sqrt(int x).
Compute and return the square root of x.

我的思路: 用折半查找的方法。

public int mySqrt(int x) {
    int first = 1;
    int last = x; 
    int result = 1;
    if(x == 0){
        return 0;
    }      
    while(first <= last){
        int mid = (first + last) / 2;                                   
        if (mid <= x / mid) {   //if(mid * mid <= x) 用这个在LeetCode上运行就会超时
            first = mid + 1;    
            result = mid;
        }
        else{
            last = mid -1;              
        }           
    }
    return result;      
}

第二种方法: 这是牛顿法,牛顿法的公式推导请看牛顿迭代法求平方根。在求解高次方程时的一种无限逼近的方法,其关键思想是:切线是曲线的近似逼近。

public int mySqrt2(int x) {
    long r = x;
    while (r*r > x)
    r = (r + x/r) / 2;
    return (int) r;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值