题目(我没想到这也能出成题目……)
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
思路
递归 比如3的5次方 = (3的2次方)的平方*3
3的4次方的3的2次方)的平方,
出口 n = 0 return 1 或 x =1return 1
收获
与操作
n&1 可以偶数奇数
代码
public class Solution {
public double myPow(double x, int n) {
// 特判,也可以认为是递归终止条件
long N = n;
if (N < 0) {
return 1 / myPow(x, -N);
}
return myPow(x, N);
}
private double myPow(double x, long n) {
if (n == 0) {
return 1;
}
if (x == 1) {
return 1;
}
// 根据指数是奇数还是偶数进行分类讨论
// 使用位运算的 与 运算符代替了求余数运算
if ((n & 1) == 0) {
// 分治思想:分
double square = myPow(x, n >>> 1);
// 分治思想:合,下面同理
return square * square;
} else {
// 是奇数的时候
double square = myPow(x, (n - 1) >>> 1);
return square * square * x;
}
}
}