Solution for sort(x) in java using binary search


  • 0
    G
    public int mySqrt(int x) {
              if (x == 0 || x == 1)
                return x;
            int start = 1, end = x/2, ans=0;
            while (start <= end)
            {
                int mid = start+(end-start) / 2;
                if (mid == x/mid)
                    return mid;
    
                if (mid < x/mid)
                {
                    start = mid + 1;
                    ans = mid;
                }
                else 
                    end = mid - 1;
            }
            return ans; 
        }
    

    At any cost, do not multiply mid with mid. It causes run time error


Log in to reply
 

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