实现这个函数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; }
浙公网安备 33010602011771号