LeetCode刷题之69. Sqrt(x)

本文介绍了一种使用二分查找算法来计算非负整数x的平方根的方法。首先尝试使用Java内置的Math.sqrt()函数,但实际问题是要返回整数部分。接着,通过二分查找策略解决这个问题,从1开始到x逐步缩小搜索范围,避免了大数值可能导致的溢出问题,最终找到最接近x平方根的整数值。

1.Description

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

2. Test Cases Example

Example 1:

Input: x = 4
Output: 2

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

3.Solution

3.1

Java里面有开方的函数,那就先试一下。(这显然不是题目要考的点)

class Solution {
    public int mySqrt(int x) {
        Double sqrt = Math.sqrt(x);
        return sqrt.intValue();
    }
}

3.2

回想自己如何预估一个整数x的平方根的过程,首先猜一个值a,然后计算a平方值,如果a的平方大于x,那么值取得太大了,可以再换一个小一点的值。直到找到一个值b,他的平方值小于x。那么x的平方根就应该在a与b之间。
但是这个方法的关键在于要能找到一个合适的a,如果是一个超级大的数字,这个初始的a该如何确定?计算机程序那就二分法找好了,但是二分法找,a的平方的值会很大,可能会超出最大整数。可以将int转换为long。

class Solution {
    public int mySqrt(int x) {
       if (x ==0 || x ==1) return x;

        long left = 1;
        long end = x;

        while (left < end) {
            long mid = (left + end ) / 2;
            if (mid * mid == x) {
                return (int)mid;
            }else if (mid * mid > x) {
                end = mid;
            } else {
                left = mid + 1;
            }
        }
        return (int)left -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值