LeetCode367 有效的完全平方数

70 阅读1分钟

题目

给定一个 正整数 num ,编写一个函数,如果 num 是一个完全平方数,则返回 true ,否则返回 false 。 进阶:不要 使用任何内置的库函数,如  sqrt 。

链接:leetcode.cn/problems/va…

示例 1:

输入:** **num = 16

输出: true

示例 2:

输入: num = 14

输出: false

解题思路

采用二分法解决

代码实现

public class Question367 {
    public static boolean isPerfectSquare(int num) {
        int left = 0;
        int right = num;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if ((long) mid * mid < num) {
                left = mid + 1;
            } else if ((long) mid * mid > num) {
                right = mid - 1;
            } else {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int x = 14;
        System.out.println(isPerfectSquare(x));
    }
}

参考

代码随想录