Java Solution using Binary Search(Like TCP's Congestion Control )


  • 0
    public boolean isPerfectSquare(int num) {
        return binarySearch((long)num, 1, 1);
    }
    
    public boolean binarySearch(long num, long curr, long anchor) {
        long multiple = curr * curr;
        if(multiple == num) {
            return true;
        } else if(multiple < num) {
            return binarySearch(num, curr * 2, curr);
        } else {
            long tmp = (anchor + curr) / 2;
            if((anchor + curr) / 2 <= anchor) return false;
            else return binarySearch(num, tmp, anchor);
        }
    }

Log in to reply
 

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