美文网首页lintcode程序员
777. Valid Perfect Square

777. Valid Perfect Square

作者: 和蔼的zhxing | 来源:发表于2018-01-31 14:47 被阅读4次

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

    注意事项

    Do not use any built-in library function such as sqrt.
    样例
    For example:
    Given num = 16
    Returns True

    二分查找

    没什么说的,二分查找基本功。

     bool isPerfectSquare(int num) {
            int beg=0;
            int end=num;
            int mid;
            while(beg<=end)
            {
                mid=beg+(end-beg)/2;
                if(pow(mid,2)==num)
                return true;
                else if(pow(mid,2)<num) beg=mid+1;
                else end=mid-1;
            }
            return false;
            // write your code here
        }
    

    相关文章

      网友评论

        本文标题:777. Valid Perfect Square

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