原题:
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10 Output: 1024.00000Example 2:
Input: 2.10000, 3 Output: 9.26100Example 3:
Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25
求幂。可以用二分求幂,注意负幂,结果:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Pow(x, n).
Memory Usage: 8.2 MB, less than 100.00% of C++ online submissions for Pow(x, n).
代码:
class Solution {
public:
double myPow(double x, long n) {
if(n<0){return 1/myPow(x,-n);}
else if(n==0){return 1;}
else if(n%2==0){
return myPow(x*x,n/2);
}
else {
return x*myPow(x,n-1);
}
}
};