Implement pow(x, n).
Solution: recursion.
1 class Solution { 2 public: 3 double pow(double x, int n) { 4 if(x < 0) return n % 2 == 0 ? pow(-x, n) : -pow(-x, n); 5 if(x == 0 || x == 1) return x; 6 if(n == 0) return 1.0; 7 if(n < 0) return 1.0/pow(x, -n); 8 9 double half = pow(x, n/2); 10 if(n % 2 == 0) return half * half; 11 else return x * half * half; 12 } 13 };