Implement pow(x, n), which calculates x raised to the power n (x^n).
Example
Solution 1
Consideration
- divide n by 2, and recursively call the function
- if n is Integer.MIN_VALUE, n = -n will overflow. So we let n/2 be -n/2. Then let x be 1/x.
class Solution {
public double myPow(double x, int n) {
if(n == 0)
return 1;
if(n == 1)
return x;
int t = n/2;
if(n < 0) {
t = -t;
x = 1/x;
}
double res = myPow(x, t);
if(n%2 == 0) return res*res;
return res*res*x;
}
}
Solution 2
Consideration
- if we use binary to represent n. We should only consider the positions where the digit is 1.
- We use this to divide n to several numbers to multiply.
class Solution {
public double myPow(double x, int n) {
// if n = Integer.MIN_VALUE, -n will overflow. So if n < 0, we decrease -n by 1.
int m = n < 0 ? -n - 1 : n;
double p = 1;
for(double q = x; m > 0; m/=2) {
if((m & 1) == 1)
p *= q;
q *= q;
}
return n < 0? 1/p/x: p;
}
}
Reference