題意:給你一個正數(shù)合砂,判斷這個正數(shù)是不是完全平方數(shù)输涕。
解題思路:“完全平方數(shù)” = 1 + 3 + 5 + 7 + 9 +...
1^2 = 1蝌数;
2^2 = 1 + 3 = (1 + 3) / 2 = 2 + 2勤家;
3^2 = 1 + 3 + 5 = (1 + 5)/2 + 3 = 3 + 3 + 3;
4^2 = 1 + 3 + 5 + 7 = (1 + 7)/2 + (3+5)/2 = 4 + 4 + 4 + 4;
...
規(guī)律就是n的平方锋喜,公式右邊就有n個數(shù)相加蘸嘶,兩端平均正好等于這個數(shù)的2倍,求和結(jié)果就是n^2;
class Solution {
public:
bool isPerfectSquare(int num) {
int i = 1;
while(num > 0)
{
num -= i;
i += 2;
}
return num == 0;
}
};