Leetcode: Pow(x, n)
Recursive solution is easier to understand. It uses the divide-and-conquer approach, which also runs in time. The formula is shown below:
And the code is quite simple and straightforward.
code:
1 class Solution { 2 public: 3 double pow(double x, int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (n == 0) 7 return 1.0; 8 double half = pow(x, n/2); 9 if (n % 2 == 0) 10 return half * half; 11 else if(n > 0) 12 return half * half * x; 13 else 14 return half * half / x; 15 } 16 };