Divide Two Integers

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


Version 1: Not that efficient for large numbers, so it cannot pass large test cases. 

public class Solution {
    public int flip(int a) {
        int neg = 0;
        int acc = (a>0) ? -1 : 1;
        while(a != 0) {
            a += acc;
            neg += acc;
        }
        return neg;
    }
    
    public int abs(int a) {
        if(a<0) return flip(a);
        else return a;
    }
    
    public int multiplication(int a, int b) {
        if(a<b) return multiplication(b, a);
        int result = 0;
        for(int i=abs(b); i>0; i--) {
            result += a;
        }
        if(b<0) result=flip(result);
        return result;
    }
    
    public int divide(int dividend, int divisor) throws java.lang.ArithmeticException {
        if(divisor==0) throw new java.lang.ArithmeticException("ERROR");
        int up=abs(dividend), down=abs(divisor), result=0, product=0;
        while(product+down<=up) {
            product += down;
            result++;
        }
        if((dividend>=0 && divisor>=0) || (dividend<0 && divisor<0)) return result;
        else return flip(result);
    }
}

Version 2: This idea copies from the the internet. Note that Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE

Here is what Java doc says for Math.abs() in javadoc :

Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE

public class Solution {
    public int divide(int dividend, int divisor) throws java.lang.ArithmeticException {
        if(divisor==0) throw new java.lang.ArithmeticException("ERROR");
        long up=Math.abs((long)dividend), down=Math.abs((long)divisor), result=0;
        while(up >= down) {
            long a = down;
            for(int i=0; up>=a; i++, a<<=1) {
                up -= a;
                result += 1<<i;
            }
        }
        return ((dividend^divisor)>>31==0) ? (int)result : (int)-result;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章