Leetcode 367) Valid Perfect Square

image

My solution

class Solution {
    public boolean isPerfectSquare(int num) {
        //What I will search here : 
        int left=0;
        int right = num;

        // I want all elements to be examined
        while(left<=right){
            int mid = left + (right-left)/2;
            //since the range of num is max int, I should use use long for this multiply, or i can divde.
            //if((long)mid*mid)
            if((double)mid ==(double) num/mid){
                return true;
            }else if((double)mid<(double) num/mid ){
                left=mid+1;
            }else{
                right = mid-1;

            }
        }

        return false;
    }
}

Other Answer

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

© 2018. All rights reserved.

Powered by Hydejack v8.5.2