Valid Perfect Square
Given a positive integernum, write a function which returns True ifnumis a perfect square else False.
Note:Do notuse any built-in library function such assqrt
.
Example 1:
Example 2:
Solution
The time complexity is O(sqrt(n)), a more efficient one using binary search whose time complexity is O(log(n)):
One thing to note is that we have to use long for mid to avoid mid * mid from overflow. Also, you can use long type for low and high to avoid type casting for mid from long to int.
And a third way is to use Newton Method to calculate the square root or num, refer to Newton Method for details.
Last updated