367. Valid Perfect Square

原题链接:https://leetcode.com/problems/valid-perfect-square/description/
实现如下:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println((long) Integer.MAX_VALUE * Integer.MAX_VALUE);
        System.out.println(s.isPerfectSquare(Integer.MAX_VALUE));
        System.out.println(s.isPerfectSquare(16));
    }

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

        return false;
    }

}
posted @ 2018-04-09 18:23  optor  阅读(128)  评论(0编辑  收藏  举报