367. Valid Perfect Square

来源:互联网 发布:深圳软件测试培训班 编辑:程序博客网 时间:2024/06/05 20:35

题目:

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: 16Returns: True

Example 2:

Input: 14Returns: False
思路:

分析规律:

1x1=1      1

2x2=4 1+3

3x3=9 1+3+5

4x4=25 1+3+5+7

nxn =  1+3+5+...(2xn-1)

代码:

class Solution {public:    bool isPerfectSquare(int num) {         int i = 1;     while (num > 0) {         num -= i;         i += 2;     }     return num == 0;            }};