Divided Int

 class Solution {// 采用位运算,用long避免溢出
public int divide(int dividend, int divisor) {
    if(divisor == 0||(dividend == Integer.MIN_VALUE && divisor == -1)){
        return Integer.MAX_VALUE;
    }
    boolean isPos = (dividend<0&&divisor>0) || (dividend>0&&divisor<0);
    long dividendl = Math.abs((long)dividend);
    long divisorl = Math.abs((long)divisor);
    int res = 0;
    while(dividendl >= divisorl){
        long tmp = divisorl;
        int mul = 1;
        while(dividendl >= (tmp<<1)){
            tmp <<= 1;
            mul <<= 1;
        }
        dividendl -= tmp;
        res += mul;
    }
    return isPos?-1 * res:res;
}

}

你可能感兴趣的:(Divided Int)