29. Divide Two Integers

class Solution {
    public int divide(int dividend, int divisor) {
        boolean positive = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0);
        System.out.println("pos: " + positive);
        long dividendLong = Math.abs((long)dividend);
        long divisorLong = Math.abs((long)divisor);

        if (dividendLong == 0 || dividendLong < divisorLong) return 0;
        if (divisorLong == 0) return Integer.MAX_VALUE;

        long ans = helper(dividendLong, divisorLong);
        if (ans >= Integer.MAX_VALUE){
            return positive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        return positive ? (int)ans : -1 * (int)ans;
    }

    private long helper(long dividend, long divisor){

        //System.out.println("dividend: " + dividend + " divisor: " + divisor);
        if (dividend < divisor) return 0;
        if (dividend == divisor) return 1;

        long element = divisor, times = 1;
        while (element + element < dividend){
            element += element;
            times += times;
        }

        //System.out.println("time: " + times);
        return times + helper(dividend - element, divisor);
    }
}

results for ""

    No results matching ""