Problem
Given a positive integer num, return true if num is a perfect square or false otherwise.
A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library function, such as sqrt.
Algorithm
Use bineary search to get the sqrt root first and then test with accuracy.
Code
class Solution:
def isPerfectSquare(self, num: int) -> bool:
L, R = 0, num
while R - L > 1e-3:
Mid = (L + R) * 0.5
if Mid * Mid > num:
R = Mid
else:
L = Mid
R = int(R)
if fabs(num - R*R) < 1e-9:
return True
else:
return False