Divide two integers

Question

from lintcode

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

If it is overflow, return 2147483647

Idea

Something I recapped due to solving this problem.

  • Bit manipulation: x << y = x * 2 ^ y in non-overflow cases

The division is basically a loop of reducing the divisors. To accelerate the speed, we can let it grow by 2's exponents with the help of << operator. Say to find z / x, we keep calculating x * 2 ^ {i} by incrementing i. When we grow too large, i.e. when x * 2 ^ i > z, we know that x * 2 ^ (i - 1) is somewhere close to the answer. Let diff = z - x * 2 ^ (i - 1) and we start another ROUND of binary-growth division on diff / x. The correct answer would be the sum of the 1 * 2 ^ (i - 1) at each ROUND.

public class Solution {
    /**
     * @param dividend: the dividend
     * @param divisor: the divisor
     * @return: the result
     */
    public int divide(int dividend, int divisor) {

        // question requirement: If it is overflow, return `2147483647`
        if(divisor == 0)
            return Integer.MAX_VALUE;

        /**
         * Integer.MIN_VALUE is -2147483648
         * Integer.MAX_VALUE +2147483647.
         * answer +2147483648 is considered out of range.
         * So we just return the maximum as requested by question.
         */
        if (dividend == Integer.MIN_VALUE && divisor == -1)
            return Integer.MAX_VALUE;

        if (dividend == 0)
            return 0;

        boolean isNegative = (dividend < 0 && divisor > 0) ||
                (dividend > 0 && divisor < 0);

        long a = Math.abs((long)dividend);
        long b = Math.abs((long)divisor);

        int result = 0;
        while (a >= b) {
            int shift = 0;
            // x << y == x * 2 ^ y
            while(a >= (b << shift))
                shift++;

            // b * 2 ^ (shift - 1) <= b * ans == a < b * 2 ^ shift
            // want to find the ans
            a -= b << (shift - 1);
            result += 1 << (shift - 1);
        }

        return isNegative? -result:result;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 一夜风雨分外凉,不用空调只开窗 今日雨停云遮阳,谁能邀我啤酒坊
    刀锋勇士阅读 89评论 0 0
  • 壮哉大象任人戏,齿利灰狼吓你慌。 体壮身强缺血性,犹如大象难成强。
    徐一村阅读 352评论 0 13
  • 坐磁悬浮列车去东京机场,在等候区的地面上有两种颜色标注排队,蓝色是马上就到的车次,红色是下一趟到达的列车,这样可以...
    明哲道阅读 371评论 0 0