Tuesday, June 10, 2014

LeetCode DivideTwoInteger

1. Avoid overflow (using long instead of int)
2. Determine the negative and positive
3. To make the code clear, using the arraylist to store all the divisors (1, 10, 100, 1000)

Here is the code:

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

//Avoid overflow
long divid = Math.abs((long)dividend);
long divs = Math.abs((long) divisor);

//Store divisors into the ArrayList
ArrayList<Long> divisors = new ArrayList<Long>();
while(divs<=divid) {
   divisors.add(divs);
   divs = divs<<1;
}

//Calculate the divide
int result = 0;
int curr = divisors.size()-1;
while (divid > 0 && curr >= 0) {
   if (divid >= divisors.get(curr)) {
       divid -= divisors.get(curr);
       result += 1<<curr;
   }
   curr--;
}

//Positive and negative sign
return (dividend > 0) ^ (divisor > 0) ? (-result) : result;

}

No comments:

Post a Comment