使用java的leetcode中的pow(x,n)

时间:2017-03-24 22:53:46

标签: java

public class Solution {
    public double myPow(double x, int n) {
        if (n == Integer.MIN_VALUE) return 0;
        if(n == 0) return 1;
        if(n == 1) return x;
        if(n < 0){
            n = -n;
            x = 1/x;
        }
        return x*myPow(x,n-1); // line 10
    }
}

以上是我的Java解决方案。但是,我不知道为什么leetcode编译器说:运行时错误消息:第10行:java.lang.StackOverflowError。

谢谢你们,伙计们。我发现问题是当n足够大时,由于减法需要花费很多时间。我应该改变二元搜索的方式。

接受的代码,但在50.44%:

public class Solution {
    public double myPow(double x, int n) {
        if(x == 1) return 1;
        if(x!=-1 && n == Integer.MIN_VALUE) return 0;
        if(x == -1 && n == Integer.MIN_VALUE) return 1;
        if(n == 0) return 1;
        if(n == 1) return x;
        if(n < 0){
            n = -n;
            x = 1/x;
        }
        return n%2==0 ? myPow(x*x, n/2):x*myPow(x*x, n/2);
    }
}

1 个答案:

答案 0 :(得分:1)

n = Integer.MAX_VALUE,x = 1 =&gt; myPow函数将被调用约Integer.MAX_VALUE -1次。 每次调用都会进行堆栈,最终会发生堆栈溢出。

尝试重写您的功能并使用while / for。

同时检查java.lang.Math.pow

相关问题