Binary Search Solution(1 ms-Java)


  • 0
    S

    My approach is select numbers to try like binary search

    public int mySqrt(int x) {
    			int start=0,end=x;
    			while(start<=end){
    				double val=(start+end)/2;
    				if(val*val==x){
    					return (int)val;
    				}
    				if(val*val>x){
    					end=(start+end)/2-1;
    				}else{
    					start=(start+end)/2+1;
    				}
    			}
    			
    			return end;
    	    }
    

Log in to reply
 

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