C# binary search, need to use long for mid, otherwise, will failed the int.max test case.


  • 0
    Y
    public class Solution {
        public int MySqrt(int x) {
            if(x<0)
                return -1;
            long left=0,right=x;
            //unit test: 0,1,2,3,4
            while(left<=right)
            {
                long mid=left+(right-left)/2;
                if(mid*mid==(long)x)
                    return (int)mid;
                if(mid*mid>(long)x)
                    right=mid-1;
                else
                    left=mid+1;
            }
            
            return (int)right;
            
        }
    }

Log in to reply
 

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