367. Valid Perfect Square(unsolved)

    xiaoxiao2021-03-25  344

    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 解答:就是二分查找,找到了就是true,否则是false

    class Solution { public: bool isPerfectSquare(int num) { if(num==0) return false; int left=1,right=num; while(left<=right) { double mid=(left+right)/2; double mul=mid*mid; if(mul==num) return true; else if(mul<num) left=mid+1; else right=mid-1; } return false; } };

    二刷时,掉入了这个坑里

    class Solution { public: bool isPerfectSquare(int num) { if(num==1) return true; int left=1,right=num; while(left<right){ long long mid=left+(right-left)/2;//一定要用long long 或者double 否则808201过不了。以后这种二分查找就用long long吧,不用int了 if(mid*mid==num) return true; else if(mid*mid<num) left=mid+1; else right=mid; } return false; } };
    转载请注明原文地址: https://ju.6miu.com/read-72.html

    最新回复(0)