标签:tco pytho 判断 coding python3 public long self perfect
两种解法:
1.单独判断1,二分法在范围[2,num/2]搜索,如果平方与num相等,则返回true
2.牛顿法
JAVA
class Solution { public boolean isPerfectSquare(int num) { if(num == 1) return true; long left = 2; long right = num/2; while(left <= right){ long mid = left + (right-left)/2; if(mid*mid == num) return true; if(mid*mid > num) right = mid-1; else left = mid+1; } return false; } }
class Solution { public boolean isPerfectSquare(int num) { if (num < 2) return true; long x = num / 2; while (x * x > num) { x = (x + num / x) / 2; } return (x * x == num); } }
Python3
class Solution: def isPerfectSquare(self, num: int) -> bool: if num == 1: return True left = 2 right = num//2 while left <= right: mid = left + (right-left)//2 if mid*mid == num: return True if mid*mid > num: right = mid - 1 else: left = mid + 1 return False
class Solution: def isPerfectSquare(self, num: int) -> bool: if num < 2: return True x = num // 2 while x * x > num: x = (x + num // x) // 2 return x * x == num
May LeetCoding Challenge9 之 求方差
标签:tco pytho 判断 coding python3 public long self perfect
原文地址:https://www.cnblogs.com/yawenw/p/12862220.html