3
头图

Effective perfect square

Title description: Given a positive integer num, write a function, if num is a perfect square number, it returns true, otherwise it returns false.

perfect square number: perfect square refers to multiplying itself by an integer such as 1*1 , 2*2 , 3*3 etc., and so on. If a number can be expressed in the form of the square of a certain integer, then the number is called a perfect square number. A perfect square number is a non-negative number, and a perfect square number has two terms.

Advanced : Do not use any built-in library functions such as sqrt for

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/valid-perfect-square/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Binary search method

Use binary search to find whether the root of num is an integer. First, declare that low is 0 and high is the square root of the largest integer. The binary search process is as follows:

  • First, low is not greater than high;
  • Declare a mid, mid is equal to (low + high) / 2 ;
  • If mid * mid == num , then num is a perfect square number, return true directly;
  • If mid * mid > num , set high to mid - 1 , and then proceed to the next round of processing;
  • If mid * mid < num , set low to mid + 1 , and then proceed to the next round of processing.

Finally, if the square of the integer is not found equal to num, it means that num is not a perfect square number, and false is returned.

public class LeetCode_367 {
    /**
     * 二分查找法
     * @param num
     * @return
     */
    public static boolean isPerfectSquare(int num) {
        int low = 1, high = (int) Math.sqrt(Integer.MAX_VALUE);
        while (low <= high) {
            int mid = (low + high) / 2;
            if (mid * mid == num) {
                return true;
            } else if (mid * mid > num) {
                high = mid - 1;
            } else if (mid * mid < num) {
                low = mid + 1;
            }
        }

        return false;
    }

    public static void main(String[] args) {
        System.out.println(isPerfectSquare(14));
    }
}
【Daily Message】 May you be loyal to yourself, live earnestly; laugh presumptuously.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!