LeetCode 029 Divide Two Integers

来源:互联网 发布:cs1.6 config 优化 编辑:程序博客网 时间:2024/06/01 12:00

题目描述

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

If it is overflow, return MAX_INT.

代码

    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;    }
1 0
原创粉丝点击