Implement pow(x, n), which calculates x raised to the power n (xn).
class Solution {
// -1 -2147483648
public double myPow(double x, int n) {
if(n == Integer.MIN_VALUE) {
if(Math.abs(Math.abs(x) - 1) < 1e-6) return 1;
return 0;
}
double result = 1.0;
boolean neg = n < 0 ? true : false;
if(neg) n = -n;
while(n != 0) {
if((n & 1) == 1) result *= x;
x *= x;
n = n >> 1;
}
if(neg) result = 1.0 / result;
return result;
}
}
public class Solution {
public double myPow(double x, int n) {
if(n == Integer.MIN_VALUE) {
if(Math.abs(Math.abs(x) - 1) < 1e-6) {
return 1;
}
return 0;
}
double result = 1.0;
if(n < 0) {
x = 1.0 / x;
n = -n;
}
while(n != 0) {
if((n & 1) == 1) result *= x;
x *= x;
n >>= 1;
}
return result;
}
}
public class Solution {
public double myPow(double x, int n) {
if(n<0) return 1/x * myPow(1/x, -(n+1));
if(n==0) return 1;
if(n==2) return x*x;
if(n%2==0) return myPow( myPow(x, n/2), 2);
else return x*myPow( myPow(x, n/2), 2);
}
}
1.0 / x
会快一些