题目难度:Easy
分类:查找
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
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
注意:不要使用任何内置的库函数,如 sqrt。
二分查找
在0~num/2+1的范围内,做二分查找
class Solution {
public:
bool isPerfectSquare(int num) {
long long left=0,right=num/2+1;
while(left <= right){
long long mid = left+(right-left)/2;
if(mid*mid == num){
return true;
}
else if(mid*mid < num){
left = mid+1;
}
else{
right = mid-1;
}
}
return false;
}
};
牛顿迭代法
牛顿迭代法wikipedia
(r+num/r)/2迭代
class Solution {
public:
bool isPerfectSquare(int num) {
long r = num;
while (r*r > num)
r = (r + num/r) / 2;
return r*r == num;
}
};