C#LeetCode刷题之#367-有效的完全平方数(Valid Perfect Square)

问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3869 访问。

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

说明:不要使用任何内置的库函数,如  sqrt。

输入:16

输出:True

输入:14

输出:False


Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Input: 16

Output: true

Input: 14

Output: false


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3869 访问。

public class Program {

    public static void Main(string[] args) {
        var n = 25;
        var res = IsPerfectSquare(n);
        Console.WriteLine(res);

        n = 17;
        res = IsPerfectSquare2(n);
        Console.WriteLine(res);

        n = 256;
        res = IsPerfectSquare3(n);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool IsPerfectSquare(int num) {
        //耍赖
        var squard = Math.Sqrt(num);
        return (int)squard - squard == 0;
        //return Math.Sqrt(num) % 1 == 0;
    }

    private static bool IsPerfectSquare2(int num) {
        //完全平方数的差都为奇数,即1,3,5,7,9...
        //完全平方数是n个奇数的和
        for(var i = 1; num > 0; i += 2) {
            num -= i;
        }
        return num == 0;
    }

    private static bool IsPerfectSquare3(int num) {
        //二分逼近,最后收敛于sqrt(x)
        long res = num;
        while(res * res > num) {
            res = (res + num / res) / 2;
        }
        return (int)(res * res) == num;
    }

}

以上给出3种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3869 访问。

True
False
True

分析:

IsPerfectSquare 的时间复杂度依赖于运行库的实现,IsPerfectSquare2 的时间复杂度为: O(n) ,IsPerfectSquare3 的时间复杂度为: O(logn) 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值