完全平方数(Valid Perfect Square)

companies

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.

简单说就是判断一个整数是否可以表示成另一个数的平方

  1. 完全平方数可以表示成从1开始的连续奇数的和。
    证明: 利用等差数列求和
class Solution {
public:
    bool isPerfectSquare(int num)
   {
        for(int i = 1; num > 0;i += 2)
        {
            num -= i;
        }
       return num == 0;
    }
};

时间复杂度

  1. 二分查找法
    判断 能否表示为 mid*mid
class Solution {
public:
    bool isPerfectSquare(int num)
    {
        int low = 1, high = num;
        long mid;
        while (low <= high)
        {
            mid = low + (high - low) / 2;
            long tmp = mid * mid;
            if (tmp == num)
                return true;
            else if (tmp > num)
                high = mid - 1;
            else
                low = mid + 1;
        }
        return false;
    }
};

时间复杂度

  1. 牛顿迭代法
class Solution {
public:
    bool isPerfectSquare(int num)
    {
        long i = num / 2 + 1;
        while (i * i > num) i = (i + num / i) / 2;
        return i * i == num;
    }
};

你可能感兴趣的:(完全平方数(Valid Perfect Square))