LeetCode题解:Divide Two Integers

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

If it is overflow, return MAX_INT.

题意:不使用乘,除,模符号作除法运算

解决思路:每一个数都可以用2进制表示,利用这一点通过位运算完成

代码:

public class Solution {
    public int divide(int dividend, int divisor) {
        if(divisor == 0){
            return Integer.MAX_VALUE;
        }else if(divisor == 1){
            return dividend;
        }else if(divisor == -1){
            return dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend;
        }else{
            final int sign = ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0))? -1 : 1;

            long lDividend = Math.abs((long)dividend);
            long lDivisor = Math.abs((long)divisor);
            int result = 0;

            for(int i = Integer.SIZE - 1; i >= 0 && lDividend >= lDivisor; i--){
                if(lDividend >= (lDivisor << i)){
                    lDividend -= lDivisor << i;
                    result |= 1 << i;
                }
            }

            return result * sign;
        }
    }
}

你可能感兴趣的:(LeetCode题解:Divide Two Integers)