为什么Divide Two Integers的对数算法在某些特殊测试用例中失败?

时间:2013-01-19 22:57:11

标签: java math

我尝试使用公式a/b = e^(ln a - ln b)来解决臭名昭着的Divide 2 Integers而不使用/%*问题,但是对于某些测试用例(dividend=Integer.MAX_VALUE or MIN_VALUE and divisor=1)我的解决方案失败了。

为什么会失败?

[编辑]:我为该测试用例得到的答案是(MAX-1 or MIN+1)。我想知道为什么会这样。

public int divide(int dividend, int divisor) {
    boolean neg = false;
    if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0))
        neg = true;

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

    double res = Math.pow(Math.E, Math.log(a) - Math.log(b));
    int ans = Math.floor(res);
    return neg ? -ans : ans;
}

1 个答案:

答案 0 :(得分:4)

问题的根源在于中间计算结果。

Double是浮点类型,当您使用它时,可能会失去精确度

在中间计算中使用double:

double res = Math.pow(Math.E, Math.log(a) - Math.log(b));
int ans = Math.floor(res);

例如,如果你使用5和1,res = 4.999999999999,Math.floor(res)将返回4.

使用Integer.MAX_VALUE,您有2147483647(原始值),但结果是2147483646.原因与5完全相同。