- Valid Perfect Square
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.
实现函数功能:检测输入的正整数是否能被完全开方,若能被完全开方则函数输出值为true
,若不能则输出false
。
注意,不能使用sqrt
等在库中已经建好的函数。
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
可利用完全平方数的性质来检测:
例如:n的平方 = 1 + 3 + 5 + 7 + 9 + 11 +…+ (2n-1)
换做图片就更好理解了,自己画了一个图。(n+1)的完全平方相比于n的完全平方,要多出(2n-1)。
------------------------------------------------------------代码如下---------------------------------------------------------------
bool isPerfectSquare(int num){
int x = 1;
while (num > 0)
{
num -= x;//逐次减去 1,3, 5, 7, 9,11....直到num>0不成立
x += 2;
}
return num == 0;//若循环结束之后num==0,这说明是完全平方数,函数输出true;若小于0,则说明不是完全平方数,函数输出false。
}