Divide Two Integers

来源:互联网 发布:程序员必学课程 编辑:程序博客网 时间:2024/06/04 19:50

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

If it is overflow, return MAX_INT.

任何一个数字都可以表示为num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n,

因而可以用移位模拟出发,除数就是a_0+a_1+a_2...的和。

public class Solution {   public static int divide(int dividend, int divisor) {    if(divisor==0) return Integer.MAX_VALUE;    if(divisor==-1 && dividend == Integer.MIN_VALUE)        return Integer.MAX_VALUE;    long pDividend = Math.abs((long)dividend);    long pDivisor = Math.abs((long)divisor);    int result = 0;    while(pDividend>=pDivisor){        //calculate number of left shifts        int numShift = 0;            while(pDividend>=(pDivisor<<numShift))            numShift++;        //dividend minus the largest shifted divisor        result += 1<<(numShift-1);        pDividend -= (pDivisor<<(numShift-1));    }    if((dividend>0 && divisor>0) || (dividend<0 && divisor<0))        return result;    else        return -result;    }}


0 0