美文网首页
367. Valid Perfect Square 平方数

367. Valid Perfect Square 平方数

作者: 这就是一个随意的名字 | 来源:发表于2017-07-30 10:52 被阅读0次

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: 16
Returns: True
Example 2:
Input: 14
Returns: False
给定正整数num,编写函数,返回num是否为平方数,要求不使用内置标准库函数。


思路
数学解法
1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
25 = 1 + 3 + 5 + 7 + 9
36 = 1 + 3 + 5 + 7 + 9 + 11
....
1+3+...+(2n-1) = (2n-1 + 1)m/2 = mn (其中m为项数 )

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

相关文章

网友评论

      本文标题:367. Valid Perfect Square 平方数

      本文链接:https://www.haomeiwen.com/subject/lmmhlxtx.html