367. Valid Perfect Square

August 19, 2016

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

题目要求我们在不使用sqrt()的情况下对一个数是否是平方数进行判断,那么有了之前实现sqrt()的经验,我们应该能想到这道题是想考察二分查找了,思路很简单,代码如下:

/*use Binary-Search,0ms*/
class Solution {
public:
    bool isPerfectSquare(int num) {
        if(num==0)
            return false;
        long long int low=0,high=num,mid=0;
        while(low<=high){
            mid=low+((high-low)>>1);
            if(mid*mid<num)
                low=mid+1;
            else if(mid*mid>num)
                high=mid-1;
            else if(mid*mid==num)
                return true;
        }
        return false;
    }
};

牛顿迭代应该也能完成,思路见69. Sqrt(x)的代码。

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017