[LeetCode]367. Valid Perfect Square

来源:互联网 发布:矩阵分解 编辑:程序博客网 时间:2024/06/05 04:25

[LeetCode]367. Valid Perfect Square

题目描述

这里写图片描述

思路

1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
….

代码

#include <iostream>using namespace std;class Solution {public:    bool isPerfectSquare(int num) {        int i = 1;        while (num > 0) {            num -= i;            i += 2;        }        return num == 0;    }};int main() {    Solution s;    cout << s.isPerfectSquare(9) << endl;    system("pause");    return 0;}