lc367. Valid Perfect Square

148 阅读1分钟

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 Output: true Example 2:

Input: 14 Output: false

思路:

1.平方数为 1+3+5+7+...n,所以只要给定num依次减去1,3,5,7,最后结果为0,即为平方数

2.牛顿法

代码:python3

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        i = 1
        while num > 0:
            num -=i
            i=i+2
        return num==0