Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

367. 有效的完全平方数* #281

Open
MyLinChi opened this issue Aug 19, 2020 · 0 comments
Open

367. 有效的完全平方数* #281

MyLinChi opened this issue Aug 19, 2020 · 0 comments

Comments

@MyLinChi
Copy link
Owner

问题

给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。

说明:不要使用任何内置的库函数,如  sqrt。

示例 1:

输入:16
输出:True
示例 2:

输入:14
输出:False

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-perfect-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一(逐个遍历查找)

class Solution {
public:
    bool isPerfectSquare(int num) {
        for(long long i=1;i*i<=num;++i)
            if(i*i == num)return true;
        return false;
    }
};

解法二(二分查找)推荐

class Solution {
public:
    bool isPerfectSquare(int num) {
        int i = 1,j=num/2;
        for(;i<=j;){
            long mid=i+((j-i)>>1);
            long long squard = mid*mid;
            if(squard == num){
                return true;
            }else if(squard > num){
                j=mid-1;
            }else{
                i=mid+1;
            }
        }
        return num==1;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant