Leetcode代码学习周记——Sqrt(x)

本文介绍了LeetCode上的一道经典算法题目:计算给定非负整数x的平方根(向下取整)。提供了三种解题思路,包括直接使用cmath库、线性搜索及高效的二分查找方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

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

题目描述:

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.


实现函数 int sqrt(int x) 计算x的平方根(返回值为一个向下取整的整数)


三种题解(第二种超时):

一:直接调用cmath库的sqrt函数,返回值使用类型转换:

#include<cmath>
class Solution {
public:
    int mySqrt(int x) {
        double result = sqrt(x);
        return (int)result;
    }
};

二:从0开始向x/2 + 1遍历,直到找到平方根:

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


三:使用二分查找找到平方根:

class Solution {
public:
    int mySqrt(int x) {
        if (x != 0) {
            int l = 1, r = 50000;
            while (1) {
                int mid = l + (r - l) / 2;
                if (mid > x / mid) r = mid - 1;
                else {
                if ((mid + 1) > (x / (mid + 1))) return mid;      
                l = mid + 1;
                }
            }
        }
        return 0;
    }
};


三种解法除了第二种会因为运行时检测不通过外均可以找到平方根,但个人认为这个题目出得不是很好,没有禁用cmath库的sqrt函数调用,很明显使用这个函数对这道题来说和作弊无疑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值