May LeetCoding Challenge9 之 求方差
两种解法:
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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步