leetcode 367. Valid Perfect Square

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.

Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

经典的二分查找:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        # find n in (1, num) that n*n == num
        # binary search
        i, j = 1, num
        while i <= j:
            mid = (i+j)>>1
            s = mid*mid
            if s == num:
                return True
            elif s > num:
                j = mid-1
            else:
                i = mid+1
        return False

 其他解法:

1
2
3
4
5
6
7
8
class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        x = int(round(math.exp(math.log(num)/2)))
        return x*x == num

 注意,int(round(xxx))是经典写法,记住!

另外的解法:A square number is 1+3+5+7+..., JAVA code,不知道这个是否数学证明过。。。

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        i = 1
        while num > 0:
            num -= i
            i += 2
        return num == 0

 最后就是牛顿法求解了。

1
2
3
4
5
6
7
8
9
10
class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        x = num;
        while (x * x > num):
            x = (x + num / x) >> 1       
        return x * x == num

但是不知道是否严密,因为num/x是整数相除,我自己倾向于下面这样解:

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        prev, cur = 0, num
        while abs(prev-cur)>1e-6:
            cur,prev=0.5*(cur+num/cur),cur
        x = int(round(cur))
        return x*x == num

 

 

posted @   bonelee  阅读(246)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-06-14 KD树——k=1时就是BST,里面的数学原理还是有不明白的地方,为啥方差划分?
2017-06-14 梯度下降法——得到的结果可能是局部最优值,如果凸函数则可保证梯度下降得到的是全局最优值
点击右上角即可分享
微信分享提示