原题
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.
题目分析
该题要求,在不适用sqrt的情况下,求出一个整数是否是完全可开方的。
思路
类似于日常生活中的猜大小,大了往小找,小了往大找,即二分法思想
代码如下
class Solution {
public:
bool isPerfectSquare(int num) {
if(num == 1){
return true;
}
int start = 0;
int end = num/2; //求根号下x,最大值不会超过n/2
while(start <= end){
long mid = start + (end-start)/2;
long res = mid*mid;
if(res == num){
return true;
}
if(res > num){
end = mid-1;
}else{
start = mid+1;
}
}
return false;
}
};
注意内容
1,在二分法中,计算mid的时候,注意int mid = (start+end)/2;可能会造成整数溢出。从而程序运行错误。
而使用int mid = start + (end-start)/2;就不会造成这样的错误。
2,在该题中,因为对于32位的来说,最大整数位2^32。此时,如果mid计算结果超过65536就会导致溢出。所以次数的res即保存mid*mid时,需要定义成long int类型。
3,在该题中,还有就是将初始的end定为n/2。否则也会导致溢出。
总结
注意边界条件,尤其是涉及大整数运算时