原题:
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: trueExample 2:
Input: 14 Output: false
判断是否是整数的平方数,我用的是二分查找:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Valid Perfect Square.
Memory Usage: 8 MB, less than 53.70% of C++ online submissions for Valid Perfect Square.
代码:
class Solution {
public:
bool isPerfectSquare(int num) {
if(num<1){return false;}
long long l=0,r=num,m=(l+r)/2;
while(l<r){
if(m*m==num){return true;}
if(m*m>num){r=m-1;m=(l+r)/2;continue;}
if(m*m<num){l=m+1;m=(l+r)/2;continue;}
}
if(m*m==num){return true;}
return false;
}
};