Share JAVA log(n) Solution no need to change type


  • 10
    W
    public class Solution {
        public int mySqrt(int x) {
            if(x <= 0) return 0;
            int l = 1, r = x, res = 1;
            while(l < r) {
                int mid = (l + r) / 2;
                if(mid > x/mid) {
                    r = mid;
                } else {
                    res = mid;
                    l = mid + 1;
                }
            }
            return res;
        }
    }
    

    Using x / mid to avoid overflow of Integer. l means left, r means right. Always have a variable res to maintain the result.


  • 0
    E
    mid = (l + r) / 2;
    

    This may result in an integer overflow. Try this instead:

    mid = l + (r - l)/2;

Log in to reply
 

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