Valid Perfect Square

http://www.lintcode.com/zh-cn/problem/valid-perfect-square/

public class Solution {
    /**
     * @param num: a positive integer
     * @return: if num is a perfect square else False
     */
    public boolean isPerfectSquare(int num) {
        // write your code here
        if (num <= 0) {
            return false;
        }
        //需要使用long,否则会出现数字溢出
        long low = 0;
        long high = num;

        while (low <= high) {
            long x = low + (high - low) / 2;
            long res = x * x;
            if (res == num) {
                return true;
            } else if (res < num) {
                low = x + 1;
            } else {
                high = x - 1;
            }
        }
        return false;
    }
}

你可能感兴趣的:(Valid Perfect Square)