代码改变世界

[LeetCode] 367. Valid Perfect Square_Easy tag:Math

2018-08-21 13:32  Johnson_强生仔仔  阅读(207)  评论(0编辑  收藏  举报

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


Use Newton Method to calculate the square root or num, refer to Newton Method for details.

Code
class Solution:
    def validSquare(self, n):
        ans = n
        while ans * ans > n:
            ans = (ans + n/ans)//2
        return ans **2 == n