描述
Given a positive integer num
, write a function which returns True
if num is a perfect square else False
.
Do not
use any built-in library function such as sqrt.
您在真实的面试中是否遇到过这个题?
是
样例
For example:
Given num = 16
Returns True
这道题没有什么难度,但是,正是这种充满无限可能的题,引发了大家的花式解法。
这道题论坛上有时间复杂度接近O(1)的解法。。。
我这里贴一个O(lgn)的解法,也就是二分法。
class Solution {
public:
/**
* @param num: a positive integer
* @return: if num is a perfect square else False
*/
bool isPerfectSquare(int num) {
// write your code here
long x = num;
while (x * x > num) {
x = (x + num / x) / 2;
}
return x * x == num;
}
};