Implement pow(x, n).
Notice
You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than 1e-3
.
Have you met this question in a real interview?
Yes
Example
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1
LeetCode上的原题,请参见我之前的博客Pow(x, n)。
解法一:
class Solution {
public:
/**
* @param x the base number
* @param n the power number
* @return the result
*/
double myPow(double x, int n) {
if (n == ) return ;
double half = myPow(x, n / );
if (n % == ) return half * half;
else if (n > ) return half * half * x;
else return half * half / x;
}
};
解法二:
class Solution {
public:
/**
* @param x the base number
* @param n the power number
* @return the result
*/
double myPow(double x, int n) {
if (n == ) return ;
if (n == ) return x;
if (n == -) return / x;
return myPow(x, n / ) * myPow(x, n - n / );
}
};