题解思路:
- 1、直接暴力求值
- 2、快速幂(附上大佬博客,仅供参考)
- 目的:速幂的目的就是做到快速求幂
举个例子:
2^9 其中9是可以拆分的9 = 2^3 + 2^0 ; 9的二进制为1001
所以2^9 = 2^1 * 2^( 2^3)
我们将原来需要9次的运算简化到了2- 思路: 据二进制的权值来求解的。那么在关于位运算的部分,我们可以逐位获取b的位,碰到0,就累乘
Java
1、暴力
public class Solution {
public double Power(double base, int exponent) {
return Math.pow(base,exponent);
}
}
2、快速幂
public class Solution {
public double Power(double base, int exponent) {
boolean flag = true;
if(exponent == 1){
return 1;
}else if(exponent<0){
exponent*=-1;
flag=false;
}
double ans = 1;
while(exponent > 0){
if(exponent%1==0){
ans = ans * base;
}
base = base * base;
exponent >>= 1;
}
return flag?ans:(1.0/ans);
}
}
Python
1、暴力
class Solution:
def Power(self, base, exponent):
return pow(base,exponent)#调用了内置函数pow()