8

LeetCode-367-有效的完全平方数

 2 years ago
source link: https://segmentfault.com/a/1190000040728457
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

LeetCode-367-有效的完全平方数

发布于 9 月 24 日

有效的完全平方数

题目描述:给定一个 正整数 num ,编写一个函数,如果 num 是一个完全平方数,则返回 true ,否则返回 false 。

完全平方数:完全平方指用一个整数乘以自己例如1*12*23*3等,依此类推。若一个数能表示成某个整数的平方的形式,则称这个数为完全平方数。完全平方数是非负数,而一个完全平方数的项有两个。

进阶不要 使用任何内置的库函数,如 sqrt 。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:二分查找法

用二分查找的方法来寻找num的开方是否是一个整数。首先,声明low为0,high为最大整数的平方根,二分查找的过程如下:

  • 首先,low不大于high;
  • 声明一个mid,mid等于(low + high) / 2
  • 如果mid * mid == num,则说明num是一个完全平方数,直接返回true;
  • 如果mid * mid > num,则将high设置为mid - 1,然后进行下一轮处理;
  • 如果mid * mid < num,则将low设置为mid + 1,然后进行下一轮处理。

最后,如果没找到整数的平方等于num,则说明num不是一个完全平方数,返回false。

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));
    }
}

【每日寄语】 愿你忠于自己,活的认真;笑得放肆。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK