实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,x^n)
https://leetcode-cn.com/problems/powx-n/
示例1:
示例2:
示例3:
提示:
Java解法
package sj.shimmer.algorithm.ten_3;
/**
* Created by SJ on 2021/2/23.
*/
class D30 {
public static void main(String[] args) {
System.out.println(myPow(-2.00000 ,2));
System.out.println(myPow(2.0000, -2));
System.out.println(myPow(2.0000, 10));
System.out.println(myPow(2.1000, 3));
System.out.println(myPow(1, 2147483647));
}
public static double myPow(double x, int n) {
if (x==1) {
return 1;
}
if (x==-1) {
if (n%2==0) {
return 1;
}
return -1;
}
if (x == 0) {
return 0;
}
if (n == 0) {
return x > 0 ? 1 : -1;
}
if (n == 1) {
return x;
}
if (n == -1) {
return 1/x;
}
boolean isPostive = n>0;
int spilt = n / 2;
double temp = myPow(x, spilt);
double single = 1;
if (n % 2!=0) {
single = myPow(x, n % 2);
}
x = temp*temp * single;
return x;
}
}
官方解
https://leetcode-cn.com/problems/powx-n/solution/powx-n-by-leetcode-solution/
-
快速幂 + 递归
- 时间复杂度:O(logn)
- 空间复杂度:O(logn)
-
快速幂 + 迭代