My Java Binary Search 0ms Solution


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

Log in to reply
 

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