0ms binary search based solution


  • 3
    I
    public boolean isPerfectSquare(int x) {
            if(x <= 0) throw new IllegalArgumentException();
            if(x == 1) return true;
            int hi = x;
            int lo = 1;
            while(lo <= hi){
                int mid = lo + (hi - lo)/2;
                if(mid * mid == x) return true;
                int div = x/mid;
                if(div >= mid){
                    lo = mid + 1;
                }
                if(div < mid){
                    hi = mid - 1;
                }
            }
            return false;
       }

Log in to reply
 

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