Friday, February 7, 2014

Divide Two Integers

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

Solution:
Brute-Force: add up divisor until it equals dividend. Return add up times. O(n)
Improvement: add up multiples of divisor as long as it doesn't greater than dividend. O(lgn)
e.g. 80: 8 + (8+8) + ((8+8)+(8+8)) +   (((8+8)+(8+8)) + ((8+8)+(8+8))) exceeds..go back
            + (8+8)  got it !!!
Tips: signs, big number. 

public class Solution {
    public int divide(int dividend, int divisor) {
        // check before converting its type to long
        boolean flag = true;
        if( (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) ) 
            flag = false;
            
        // test data: -1010369383, -2147483648
        long y = dividend;
        long x = divisor;
            
        x = x < 0 ? -x : x;
        y = y < 0 ? -y : y;
        
        int count = 0;
        while(y >= x){
            long sum = x;
            int i = 1;
            while(y >= sum){
                y -= sum;
                count += i;
                
                // add up divisor to reduce time 
                sum += sum;
                i += i;
            }
        }
        
        if(!flag) count = -count;
        return count;
    }
}

No comments:

Post a Comment