Leetcode 题目解析之 Divide Two Integers

2022-01-15 12:12:51 浏览数 (2)

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

If it is overflow, return MAX_INT.

代码语言:javascript复制
    public int divide(int dividend, int divisor) {
        if (divisor == 0) {
            return Integer.MAX_VALUE;
        }
        int result = 0;
        if (dividend == Integer.MIN_VALUE) {
            result = 1;
            if (divisor == -1) {
                return Integer.MAX_VALUE;
            }
            dividend  = Math.abs(divisor);
        }
        if (divisor == Integer.MIN_VALUE) {
            return result;
        }
        boolean isNeg = ((dividend ^ divisor) >>> 31 == 1) ? true : false;
        dividend = Math.abs(dividend);
        divisor = Math.abs(divisor);
        int c = 0;
        while (divisor <= (dividend >> 1)) {
            divisor <<= 1;
            c  ;
        }
        while (c >= 0) {
            if (dividend >= divisor) {
                dividend -= divisor;
                result  = 1 << c;
            }
            divisor >>= 1;
            c--;
        }
        System.out.println(result);
        return isNeg ? -result : result;
    }

0 人点赞