Java binary search solution beats 98%


  • 1
    J
    public class Solution {
        public int divide(int dividend, int divisor) {
            int sign=(dividend>0&&divisor>0)||(dividend<0&&divisor<0)?1:-1;
            long divd=Math.abs((long)dividend),divi=Math.abs((long)divisor);
            long res=0,lo=1,hi=divd;
            while(lo<=hi){
                long mid=lo+(hi-lo)/2;
                if(mid*divi<=divd){
                    res=mid;
                    lo=mid+1;
                }else{
                    hi=mid-1;
                }
            }
            return res*sign==2147483648L?Integer.MAX_VALUE:(int)res*sign;
        }
    }
    

  • 0
    A

    Read the question, it said NOT to use any multiplication or division. Kinda defeats the whole purpose doesn't it?


Log in to reply
 

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