俊介三

一天更新一点,一天积累一点

导航

Pow(x,n)

Posted on 2013-03-11 20:41  俊介三在前进  阅读(166)  评论(0)    收藏  举报

实现这个函数pow(double x, int n)

http://discuss.leetcode.com/questions/228/powx-n

有几点要注意:

1.n是整数,可以是正、负和0

2.x可以为0

3.使用divide and conquer.是的,一次for循环从0到|n|会超时,把它分成两半,时间复杂度立即减半

代码入下:

double pow(double x, int n) {
    // A trick to avoid -INT_MIN underflow
    if (n < 0) return 1.0 / pow(x, -(n+1)) / x;
    if (n == 0) return 1.0;
    // Compute x^{n/2} and store in a variable to avoid redundant computing
    double y = pow(x, n / 2);
    if (n % 2 == 0)
        return y * y;
    else
        return y * y * x;
}