Valid Perfect Square

来源:互联网 发布:易语言源码与模块解析 编辑:程序博客网 时间:2024/04/29 09:11

题目地址:https://leetcode.com/problems/valid-perfect-square/?tab=Description

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,那就方便多了:

public class ValidPerfectSquare {    public boolean isPerfectSquare(int num) {        int temp = (int) Math.sqrt(num);        if (temp * temp == num)            return true;        else             return false;    }}

但是人家说了,不让用内置的方法,那只能想其他办法了,从0num慢慢往上扫呗,可是这个速度貌似有点慢。

我们知道一般在[0,num/2]这个区间就能找到num的根,所以我们可以用二分法区定位num的二次根,这样的话速度就大大提高了:

public class ValidPerfectSquare {    public static boolean isPerfectSquare(int num) {        int l = 0;        int h = 46340; // (int)Math.sqrt(Integer.MAX_VALUE);        while (l <= h) {            if (l * l == num ||h * h == num)                return true;            int m = l + (h - l) / 2;            if (m * m > num)                h = m - 1;            else if (m * m == num)                return true;            else                l = m + 1;        }        return false;    }    public static void main(String[] args) {        for (int i = 2146225; i <= 2146225; i++)            System.out.println(i + " " + isPerfectSquare(i));    }}

注意这里可能整型溢出的情况,为了避免这个情况的发生,我们索性就在Integer这个范围内找。

0 0
原创粉丝点击