Press "Enter" to skip to content

Valid Perfect Square-LeetCode#367

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
Output: true

Example 2:

Input: 14
Output: false

思路:给定一个正整数,判断该数字是否能开平方根,且根为整数。题目要求不能用内置方法sqrt。二分查找法。

代码如下:

public static boolean isPerfectSquare(int num) {
    if (num == 1) return true;
    int start = 1;
    int end = num;
    while (start <= end){
        int mid = start + (end - start) / 2;
        if (mid * mid == num){
            return true;
        }else if (mid * mid < num){
            start = mid + 1;
        }else if (mid * mid > num){
            end = mid - 1;
        }
    }
    return false;
}

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注