Pow(x, n)
Implement pow(x, n).
Runtime: 23ms
1 class Solution { 2 public: 3 /** 4 * @param x the base number 5 * @param n the power number 6 * @return the result 7 */ 8 double myPow(double x, int n) { 9 // Write your code here 10 if (x == 0) return 0; 11 if (n == 0) return 1; 12 if (n == 1) return x; 13 if (n == -1) return 1 / x; 14 15 double temp = myPow(x, n / 2); 16 return temp * temp * myPow(x, n % 2); 17 } 18 };
Analyse: Be aware of corner cases. For exmaple, x = 0, n = 0, n = 1, and n < 0. Note the highlited area, if n == INT_MIN, we have to use braces to ensure the correctness.
Runtime: 4ms.
1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 if(!x) return 0.0; 5 if(!n) return 1.0; 6 if(n == 1) return x; 7 8 if(n < 0) { 9 double temp = myPow(1 / x, -(n / 2)); 10 return temp * temp * myPow(1 / x, -(n % 2)); 11 } 12 else{ 13 double temp = myPow(x, n / 2); 14 return temp * temp * myPow(x, n % 2); 15 } 16 } 17 };