Accepted Java solution without using long or unsigned int.


  • 0
    F
    public class Solution {
        public int divide(int dividend, int divisor) {
                    if (dividend == Integer.MIN_VALUE && divisor == -1) { // overflow case
    			return Integer.MAX_VALUE;
    		}
    		if (dividend == 0) { // trivial case
    			return 0;
    		}
    		if (dividend == Integer.MIN_VALUE && divisor == Integer.MIN_VALUE) { // both are int_min
    			return 1;
    		}
    		if (divisor == Integer.MIN_VALUE) { // only divisor is int_min
    			return 0;
    		}
    		boolean isNeg = true;
    		if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
    			isNeg = false;
    		}
    		if (divisor < 0) {
    			divisor = 0 - divisor; // here, divisor is never gonna overflow
    		}
    		int ans = 0;
    		if (dividend == Integer.MIN_VALUE) { // only dividend is int_min
    			dividend = Integer.MAX_VALUE - (divisor - 1);
    			ans++;
    		} else {
    			if (dividend < 0) {
    				dividend = 0 - dividend; // here, dividend is never gonna overflow
    			}
    		}
    		while (dividend >= divisor) {
    			int shift = 0;
    			while (dividend >= (divisor << shift)) {
    				shift++;
    				int v = divisor << (shift - 1);
    				if(v > (Integer.MAX_VALUE - v)) {
    					break;
    				}
    			}
    			dividend -= divisor << (shift - 1);
    			ans += 1 << (shift - 1);
     		}
    		return isNeg ? (0 - ans) : ans;
        }
    }
    

Log in to reply
 

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