Clean Java solution without Long


  • 0
    G
    public class Solution {
        public int divide(int dividend, int divisor) {
            
            // when divisor == Integer.MIN_VALUE, only have two possible results
            if (divisor == Integer.MIN_VALUE) {
                if (dividend == Integer.MIN_VALUE) {
                    return 1;
                }
                
                return 0;
            }
            
            boolean neg = false;
            int q = 0;
            int remainder = dividend;
    
            if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {
                neg = true;
            }
            
            while (true) {
                int partQ = neg ? -1 : 1;
                // diviosor != Integer.MIN_VALUE, so Math.abs(divisor) will not overflow
                int partR = dividend < 0 ? -Math.abs(divisor) : Math.abs(divisor);
                int shiftStep = 0;
    
                while (true) {
                    int curQ = partQ << shiftStep;
                    int curR = partR << shiftStep;
                    
                    // exceed remainder, discard
                    if (dividend < 0 && curR < remainder) {
                        break;
                    }
                    
                    if (dividend >= 0 && curR > remainder) {
                        break;
                    }
                                    
                    shiftStep = shiftStep + 1;
                    
                    // when current q greater than Integer.MAX_VALUE / 2, next loop will over flow, stop loop
                    if (curQ > (Integer.MAX_VALUE >> 1) || curQ < (Integer.MIN_VALUE >> 1)) {
                        break;
                    }
                    
                    if (curR > (Integer.MAX_VALUE >> 1) || curR < (Integer.MIN_VALUE >> 1)) {
                        break;
                    }
                }
                
                if (shiftStep > 0) {
                    int curQ = partQ << (shiftStep - 1);
                    
                    if (curQ >= (Integer.MAX_VALUE >> 1) && q >= (Integer.MAX_VALUE >> 1)) {
                        return Integer.MAX_VALUE;
                    }
                    
                    q = q + curQ;
                    remainder = remainder - (partR << (shiftStep - 1));
                }
                
                if (Math.abs(remainder) < Math.abs(divisor)) {
                    break;
                }
            }
            
            return q;
        }
    }
    

Log in to reply
 

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