Simple BS solution in java


  • 0
    V

    Normal binary search if number has integral square root but problems arise when it doesn't have an integral square root it narrows down to a number from which subtracting 1 will give you the floor of the square root

    public class Solution {
        public int mySqrt(int x) {
            
            int l = 1;
            int r = x;
            if(x==0) return 0;
            while(l<r) {
                int m = l+(r-l)/2;
                if(m==x/m) return m;
                else if(m<x/m) l = m+1;
                else r = m;
            }
            return l-1;
        }
    }
    

Log in to reply
 

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