Skip to content

367 valid perfect square

367. Valid Perfect Square

题目:

https://leetcode.com/problems/valid-perfect-square/

难度:

Medium

直接用循环做也可以AC

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num == 1 or num == 4 : return True
        for i in xrange(num//2):
            if i*i == num:
                return True
            elif i*i > num:
                return False
        return False

然后发现有传说中的牛顿法

有待阅读,然后还有二分法

    r = x
    while r*r > x:
        r = (r + x/r) / 2
    return r*r == x


回到顶部