版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuqiuai/article/details/83096286
题目链接:https://leetcode-cn.com/problems/powx-n/description/
题目描述
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例
输入: 2.00000, 10
输出: 1024.00000
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
- -100.0 < x < 100.0
- n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
解决方法
用递归
class Solution {
public:
double myPow(double x, int n) {
//利用递归
if(n<0)
return 1/power(x,-n);
else
return power(x,n);
}
private:
double power(double x, int n){
if (n==0) return 1;
else if (n%2==0) return power(x,n/2)*power(x,n/2);
else return power(x,n/2)*power(x,n/2)*x;
}
};