首页 > 其他 > 详细

LeetCode 第 367 题 (Valid Perfect Square)

时间:2016-07-13 16:28:53      阅读:114      评论:0      收藏:0      [点我收藏+]

LeetCode 第 367 题 (Valid Perfect Square)

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

这道题可以借用第 69 题的代码。第 69 题中我们实现了自己的 Sqrt 函数,既然这道题不让用库函数中的 sqrt,那么我们就自己写个,用简单的二分查找法就可以。代码的具体解释见第 69 题的解答。

下面是代码。

int mySqrt(int x)
{
    if(x <= 0) return 0;
    int a1 = 1;
    int a2 = 46341 * 2 - 1;
    unsigned int a, y;
    if(a2 > x / 2) a2 = x;
    do
    {
        a = (a1 + a2) / 2;
        y = a * a;
        if(y == x) return a;
        if(y > x)
        {
            a2 = a;
        }
        else
        {
            a1 = a;
        }
    }while(a1 + 1 < a2);
    a = (a1 + a2) / 2;
    return a;
}
bool isPerfectSquare(int num) 
{
    int z = mySqrt(num);
    return z * z == num;
}

LeetCode 第 367 题 (Valid Perfect Square)

原文:http://blog.csdn.net/liyuanbhu/article/details/51892285

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!