C# LeetCode刷题 - Leetcode367. 有效的完全平方数 - 题解

本文介绍了一种不使用内置sqrt函数判断一个数是否为完全平方数的方法,并提供了两种高效的解决方案,包括数学公式法和Babylonian method。

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

版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址
http://blog.youkuaiyun.com/lzuacm。

C#版 - Leetcode367. 有效的完全平方数 - 题解

Leetcode 367 - Valid Perfect Square

在线提交:
https://leetcode.com/problems/valid-perfect-square/

题目描述


给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。

注意: 不要使用任何内置的库函数,如 sqrt

示例 1:

输入: 16

输出: True

示例 2:

输入: 14

输出: False


**归功于:**

特别感谢 @elmirap 添加此问题并创建所有测试用例。


  ●  题目难度: 简单

思路:

首先题目明确要求不能使用内置的sqrt及其他相关的库函数,于是解此题常见的几种方法如下:

1.利用数学公式 $k^2 = 1 + 3 + \cdots +(2\cdot k - 1) $ .

2.自己实现sqrt函数的功能,最快的方法当属 Babylonian method.

3.二分查找


方法1 已AC代码:
public class Solution
{
    public bool IsPerfectSquare(int num)
    {
        int i = 1;
        while (num > 0)
        {
            num -= i;
            i += 2;
        }

        if (num == 0)
            return true;
        return false;
    }
}

Rank:
You are here! Your runtime beats 94.68 % of csharp submissions.


方法2 已AC代码:
public class Solution
{
    public const double eps = 1e-10;
    public bool IsPerfectSquare(int num)
    {
        double sq1 = SquareRoot(num);
        int sq2 = (int)SquareRoot(num);
        if (sq1 - (double)sq2 < eps && sq1 - (double)sq2 > -eps)
            return true;
        return false;
    }
    public double SquareRoot(double x)
    {
        if (x == 0)
            return 0;

        double r = x / 2; 
        double last = 0;
        int maxIters = 100;

        for (int i = 0; i < maxIters; i++)
        {
            r = (r + x / r) / 2;
            if (r - last < eps && r - last > -eps)
                break;

            last = r;
        }

        return r;
    }
}

Rank:
You are here! Your runtime beats 94.68 % of csharp submissions


dotNET匠人 公众号名片

文末彩蛋

微信后台回复“asp”,给你:一份全网最强的ASP.NET学习路线图。


回复“cs”,给你:一整套 C# 和 WPF 学习资源!


回复“core”,给你:2019年dotConf大会上发布的.NET core 3.0学习视频!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

极客白小飞

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

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

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

打赏作者

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

抵扣说明:

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

余额充值