Implement pow(x, n).
用二分法,O(logn)。注意n < 0的处理
1 class Solution { 2 public: 3 double power(double x, int n) 4 { 5 if (n == 0) 6 return 1; 7 8 double v = power(x, n / 2); 9 10 if (n % 2 == 0) 11 return v * v; 12 else 13 return v * v * x; 14 } 15 16 double pow(double x, int n) { 17 // Start typing your C/C++ solution below 18 // DO NOT write int main() function 19 if (n < 0) 20 return 1.0 / power(x, -n); 21 else 22 return power(x, n); 23 } 24 };