闯关leetcode——69. Sqrt(x)

题目

地址

https://leetcode.com/problems/sqrtx/description/

内容

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Example 1:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since we round it down to the nearest integer, 2 is returned.

Constraints:

  • 0 <= x <= 231 - 1

解题

这题是要求小于等于一个数的最大平方数。比如9、10、11……15对应的数字都是3,而16对应的数是4。
因为平方数没有太多的规律,所以基本就是挨个尝试来逼近结果。这种问题一般使用二分查找法,解法非常类似于《闯关leetcode——35. Search Insert Position》,主要区别就是我们要返回边界触发时左侧边界。
但是这题解法还是有一定的优化空间,这就涉及二进制相关知识。比如数字16,它的二进制是0x10000,即1左移4次。它也可以表达为1左移2次的数(4)的平方;再比如17,它的二进制是0x10001。它一定比1左移2次的平方大,比1左移3次平方小(这个很好证明)。我们就可以在最开始时分析这个数的二进制中最高位的1所在的位,来限制我们二分查找的区间。
这题还有一个陷阱就是:警惕探索过程中数字乘积越过类型界限。我们在本例的二分查找中就使用了更大的类型来避免这个坑。

class Solution {
public:
    int mySqrt(int x) {
        if (x == 0) return 0;
        int num = x;
        int i = 1;
        for (; num > 0; i++) {
            num >>= 1;
        }
        
        int start = 0;
        if (i > 2) {
            start = 1 << (i / 2 - 1);
        } else {
            start = 1 << 0;
        }

        int end = start << 1;
        return binarySearch(start, end, x);
    }
private:
    int binarySearch(unsigned long long start, unsigned long long end, unsigned long long x) {
        unsigned long long mid = (start + end) / 2;

        if (start > end) return end;

        unsigned long long result = mid * mid;
        if (result == x) return mid;
        if (result < x) return binarySearch(mid + 1, end, x);
        return binarySearch(start, mid - 1, x);
    }
};

在这里插入图片描述

代码地址

https://github.com/f304646673/leetcode/tree/main/69-Sqrt(x)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

breaksoftware

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值