leetcode_367
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
Output: true
Example 2:
Input: 14
Output: falseSolutions
The problem is equivalent to calculating the square root of the given number.
See problem 69 for details.
newton's method
class Solution {
public:
bool isPerfectSquare(int num) {
long root = num;
while (root * root > num) {
root = (root + num / root) / 2;
}
return root * root == num;
}
};binary search
Last updated
Was this helpful?