LeetCode

Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

Java

public class Solution {
    public int divide(int dividend, int divisor) {
        if(divisor == 0) {
            return Integer.MAX_VALUE;
        }
        if(divisor == -1 && dividend == Integer.MIN_VALUE) {
            return Integer.MAX_VALUE;
        }

        long p = (long) Math.abs((long) dividend);
        long q = (long) Math.abs((long) divisor);

        int rst = 0;
        while(p >= q) {
            int count = 0;
            while(p >= (q << count)) {
                count++;
            }
            rst += 1 << (count - 1);
            p -= q << (count - 1);
        }
        if((dividend ^ divisor) < 0) {
            return -rst;
        } else {
            return rst;
        }
    }
}