Skip to content

Latest commit

 

History

History
36 lines (36 loc) · 1.06 KB

29.md

File metadata and controls

36 lines (36 loc) · 1.06 KB

#29. Divide Two Integers 题目链接

public class Solution {
    public int divide(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
            return Integer.MAX_VALUE;
        }
        long dividendL = (long)dividend;
        long divisorL = (long)divisor;
        boolean positive = (dividendL>0&&divisorL>0) || (dividendL<0&&divisorL<0) ? true : false;
        dividendL = Math.abs(dividendL);
        divisorL = Math.abs(divisorL);
        int result = 0;
        int n = 1;
        // 利用位操作来实现乘二除二的效果
        while (dividendL >= 0) {
            long tmp = dividendL - divisorL;
            if (tmp < 0 && n != 1) {
                n >>= 1;
                divisorL >>= 1;
                continue;
            }
            dividendL = tmp;
            result += n;
            n <<= 1;
            divisorL <<= 1;
        }
        result--;
        if (positive) {
            return result;
        }
        return -result;
    }
}