Java O(logn) binary search using "long"


  • 0

    The reason to use long is that for large number such as 808201
    the mid * mid will be out of Integer.MAX_VALUE range.

    public class Solution {
        public boolean isPerfectSquare(int num) {
            long start = 1;
            long end = num;
            while (start < end) {
                long mid = start + (end - start) / 2;
                if (mid * mid == num) {
                    return true;
                } else if (mid * mid < num) {
                    start = mid + 1;
                } else {
                    end = mid;
                }
            }
            return start * start == num;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.