LeetCode每日一题:divide two integer

2017-07-03  本文已影响76人  yoshino

问题描述

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

问题分析

这题让我们模拟除法,最简单的方式是采用减法代替除法,但是这样做会超时,所以只能使用二进制位运算来翻倍除数,从而加快运算。

代码实现

public int divide(int dividend, int divisor) {
        int sign = 1;
        if (dividend < 0) sign = -sign;
        if (divisor < 0) sign = -sign;
        long temp = Math.abs((long) dividend);
        long temp2 = Math.abs((long) divisor);
        long c = 1;
        while (temp > temp2) {
            temp2 = temp2 << 1;
            c = c << 1;
        }
        int res = 0;
        while (temp >= Math.abs((long) divisor)) {
            while (temp >= temp2) {
                temp -= temp2;
                res += c;
            }
            temp2 = temp2 >> 1;
            c = c >> 1;
        }
        if (sign > 0) return res;
        else return -res;
    }
上一篇 下一篇

猜你喜欢

热点阅读