美文网首页
Divided Int

Divided Int

作者: Michaelwen003 | 来源:发表于2018-07-10 00:28 被阅读0次
     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

          本文链接:https://www.haomeiwen.com/subject/popxpftx.html