LintCode 777. Valid Perfect Square

Posted zslhg903

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LintCode 777. Valid Perfect Square相关的知识,希望对你有一定的参考价值。

Given a positive integer num, write a function which returns True if num is a perfect square else False.

 

样例

For example:
Given num = 16
Returns True

 

解法一:牛顿迭代器

class Solution {
public:
    /**
     * @param num: a positive integer
     * @return: if num is a perfect square else False
     */
    bool isPerfectSquare(int num) {
        // write your code here
        double pre=0,res=1;
        while(pre!=res)
        {
            pre=res;
            res=(res+num/res)/2;
        }
        int t=(int)res;
        return t*t==num;
    }
};

解法二:二分法

class Solution {
public:
    /**
     * @param num: a positive integer
     * @return: if num is a perfect square else False
     */
    bool isPerfectSquare(int num) {
        // write your code here
        long left=0,right=num,mid;
        while(left<=right)
        {
            mid=left+(right-left)/2;
            long res=mid*mid;
            if(res<num)
            {
                left=mid+1;
            }
            else if(res>num)
            {
                right=mid-1;
            }
            else
            {
                return true;
            }
        }
        return false;
    }
};

 

以上是关于LintCode 777. Valid Perfect Square的主要内容,如果未能解决你的问题,请参考以下文章

[LintCode] Valid Parentheses

[LintCode] Graph Valid Tree

lintcode178- Graph Valid Tree- medium

423 有效的括号序列

caffe与tensorflow中的pooling

lintcode:单词切分