welcome to my blog
LeetCode Top Interview Questions 50. Pow(x, n) (Java版; Medium)
题目描述
Implement pow(x, n), which calculates x raised to the power n (x^n).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
class Solution {
public double myPow(double x, int n) {
if(x==0){
return 0;
}
if(x==1){
return 1;
}
//
if(n==0){
return 1;
}
if(n==1){
return x;
}
//
double res = 0;
if(n<0){
if(n==Integer.MIN_VALUE){
n++;
n = -n; //Integer.MAX_VALUE
x = 1/x;
return x*x * myPow(x*x, n/2);
}else{
n = -n;
x = 1/x;
}
}
return n%2==0? myPow(x*x, n/2) : x*myPow(x*x, n/2);
}
}
第一次做; 参考了LeetCode的最优解; 这个算法也叫快速幂法
/*
核心:2^16 == 4^8
和不使用加减乘除相加有点像
*/
class Solution {
public double myPow(double x, int n) {
//base case
if(x==0)
return 0;
if(n==0)
return 1;
//自顶向下; 本题最麻烦的地方在于n=Integer.MIN_VALUE
double res = 0;
if(n<0){
if(n==Integer.MIN_VALUE){
n++;
n = -n;
x = 1/x;
return x*x*myPow(x*x, n/2);
}
else{
n = -n;
x = 1/x;
// return n%2==0?myPow(x*x, n/2) : x*myPow(x*x, n/2);
}
}
return n%2==0?myPow(x*x, n/2) : x*myPow(x*x,n/2);
}
}
第一次做; 分治; 自顶向下; 使用memo数组记录计算过的幂, 但是内存超出限制,291 / 304; 绊脚案例:x=0.00001, n=2147483647; 看来需要自底向上?
class Solution {
public double myPow(double x, int n) {
double res=1;
if(x==0)
return 0;
else{
if(n==0)
return 1.0;
//分治; 自顶向下
int tmp = Math.abs(n);
//2147483647
double[] memo = new double[tmp];
res = core(memo, x, tmp);
}
return n>0?res : 1/res;
}
public double core(double[] memo, double x, int n){
//base case
if(n==0)
return 1;
if(n==1)
return x;
if(memo[n-1]!=0)
return memo[n-1];
//
double leftRes = core(memo, x, n/2);
double rightRes = core(memo, x, n-n/2);
memo[n-1] = leftRes*rightRes;
return memo[n-1];
}
}
第一次做; 循环版竟然超时; 291 / 304; 看样子得改成分治法
/*
求幂
按照底数是否为0分成两种情况讨论
*/
class Solution {
public double myPow(double x, int n) {
double res=1;
if(x==0)
return 0;
else{
if(n==0)
return 1.0;
for(int i=0, m=Math.abs(n); i<m; i++){
res = res * x;
}
}
return n>0?res : 1/res;
}
}
快速幂算法; 自底向上; 来自力扣题解
class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double ans = 1;
double current_product = x;
for (long i = N; i > 0; i /= 2) {
if ((i % 2) == 1) {
ans = ans * current_product;
}
current_product = current_product * current_product;
}
return ans;
}
};