题目
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
思路
二分法,注意边界条件:
1. 可能溢出 要用long long
2. 输入0,输出false;输入1,输出true
代码:
class Solution {
public:
bool isPerfectSquare(int num) {
long long right=num/2+1;
long long left = 0;
if(num==0||num==1){
return (bool)num;
}
while(left<=right){
long long mid = (left+right)/2;
long long mul=mid*mid;
if(num == mul){
return true;
}
if(num<mul){
right = mid-1;
}else{
left = mid+1;
}
}
return false;
}
};
同类型题:https://blog.csdn.net/tan_change/article/details/80148107