题目描述:
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
Returns: True
Example 2:
Input: 14
Returns: False
判断一个数是不是完全平方数,从大到小搜索时间复杂度为O(n),采用二分搜索时间复杂度为O(nlog n)。
class Solution {
public:
bool isPerfectSquare(int num) {
int begin=0;
int end=num;
while(begin<=end)
{
long long mid=(begin+end)/2;
if(mid*mid==num) return true;
else if(mid*mid<num) begin=mid+1;
else end=mid-1;
}
return false;
}
};