题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
解法1:调用库函数
import java.util.*;
public class Solution {
public double Power(double base, int exponent) {
return Math.pow(base,exponent);
}
}
解法2:暴力法
import java.util.*;
public class Solution {
public double Power(double base, int exponent) {
if(exponent < 0){
base = 1 / base;
exponent = -exponent;
}
double a = 1.0;
for(int i = 0;i<exponent;i++){
a = a * base;
}
return a;
}
}
解法3:递归法(快速幂)
package test;
import java.util.ArrayList;
class Solution {
public double q_power(double b, int n) {
if (n == 0) return 1.0;//递归的停止条件
double ret = q_power(b, n/2);
if (n % 2 != 0) { // 奇数
return ret * ret * b;
}
else {
return ret * ret;
}
}
double Power(double b, int n) {
if (n < 0) {
b = 1 / b;
n = -n;
}
return q_power(b, n);
}
};
public class Main{
public static void main(String[] args) {
Solution solution = new Solution();
// int []a = {1,0,1,1,1};
int a = 5;
double b = solution.q_power(2,4);
System.out.print("最小值是:" + b);
}
}
解法4:非递归的快速幂(不太好理解)
package test;
import java.util.ArrayList;
class Solution {
public double Power(double b, int n) {
if (n < 0) {
b = 1 / b;
n = -n;
}
double x = b; // 记录x^0, x^1, x^2, x^4, x^8,...
double ret = 1.0;
while (n!=0) {
if (n%2!=0) {
ret *= x; // 二进制位数是1的,乘进答案。
}
x *= x;//这个地方很关键,后一个都是前一个的平方
n >>= 1;
}
return ret;
}
};
public class Main{
public static void main(String[] args) {
Solution solution = new Solution();
// int []a = {1,0,1,1,1};
int a = 5;
double b = solution.Power(3,7);
System.out.print("最小值是:" + b);
}
}