Implement pow(x, n).
» Solve this problem[解题思路]
二分法,注意n<0的情况。
[Code]
1: double power(double x, int n)
2: {
3: if (n == 0)
4: return 1;
5: double v = power(x, n / 2);
6: if (n % 2 == 0)
7: return v * v;
8: else
9: return v * v * x;
10: }
11: double pow(double x, int n) {
12: // Start typing your C/C++ solution below
13: // DO NOT write int main() function
14: if (n < 0)
15: return 1.0 / power(x, -n);
16: else
17: return power(x, n);
18: }