29. Divide Two Integers

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

If it is overflow, return MAX_INT.

1. nagitive

2. overflow

Another example : 10 / 3 = 3

1st outer loop
--------------

1st inner loop --- tmp = 6 , count = 2
2nd inner loop --- tmp = 12, count = 4 (exit the inner loop, result = 0 + (4 >> 1) = 2)

dividend = 10 - (12 >> 1) = 10 - 6 = 4 (4 >  divisor, so here we go second outer loop)

2nd outer loop
--------------

1st inner loop --- tmp = 6, count = 2 (exit the inner loop, result = 2 + (2 >> 1) = 3)

dividend = 4 - (6 >> 1) = 4 - 3 = 1( divisor > 1, exit outer loop, return result)
public class Solution {
    public int divide(int dividend, int divisor) {
        boolean isNagative = false;
        if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) isNagative = true;
        long absDivisor = Math.abs((long)divisor);
        long abdDividend = Math.abs((long)dividend);
        long res = 0;
        while(absDivisor <= abdDividend){
            long temp = absDivisor; 
            long cnt = 1;
            while(temp <= abdDividend){
                temp <<= 1;
                cnt <<= 1;
            }
            res += cnt >> 1;
            abdDividend -= temp>>1 ;
        }
        if(isNagative)
          res = ~res + 1;
        if (res > Integer.MAX_VALUE)
          res = Integer.MAX_VALUE;
        
         return (int) res;
    }
}
 
原文地址:https://www.cnblogs.com/joannacode/p/6116312.html