Given a positive integer num, write a function which returns True if num is a perfect square else False. 给出一个正整数,写一个函数,若该数为完全平方数,则返回True;否则返回False。 Note: Do not use any built-in library function such as sqrt. 不能使用内建函数,如sqrt。 Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
(1)1+3+5+7+.+(2*n-1) = n^2 (2)完全平方数的末位一定为0,1,4,5,6,9中的一个。
class Solution {
public:
bool isPerfectSquare(int num) {
int rest = num % 10;
if(rest == 2 || rest == 3 || rest == 7 || rest == 8)
return false;
int sum = 0;
for(int i = 1; sum < num; i = i + 2){
sum += i;
if(sum == num)
return true;
}
return false;
}
};