题目:https://leetcode-cn.com/problems/powx-n/
给定x和n,求x的n次方。
快速幂的题目,利用递归快速求解。
class Solution {
public double myPow(double x, int n) {
if(n > 0){
return quickMul(x, n);
}else {
return 1.0 / quickMul(x, n);
}
}
double quickMul(double x, int n){
if(n == 0) return 1.0;
if(n % 2 == 0){
return pow(quickMul(x, n / 2 ), 2);
}else {
return pow(quickMul(x, n / 2 ), 2) * x;
}
}
double pow(double x, double y){
double ans = 1.0;
for(int i = 0;i < y;i++){
ans *= x;
}
return ans;
}
}
进阶:超级次方