标签:creating 牛顿法 ase rip += rap mat any math
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.
经典的二分查找:
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
其他解法:
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,不知道这个是否数学证明过。。。
class Solution(object): def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ i = 1 while num > 0: num -= i i += 2 return num == 0
最后就是牛顿法求解了。
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是整数相除,我自己倾向于下面这样解:
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
leetcode 367. Valid Perfect Square
标签:creating 牛顿法 ase rip += rap mat any math
原文地址:https://www.cnblogs.com/bonelee/p/9185445.html