50. Pow(x, n)
Medium (LinkedIn, Google, Bloomberg, Facebook)
Implement pow(x, n).
public class Solution {
// test case:
// x == 1 or n == 0
// x == -1
// x == 0 or n >= Integer.MAX_VALUE or n <= Integer.MIN_VALUE
// x < 0 or n < 0
public double myPow(double x, int n) {
if(x == 1 || n == 0) {
return 1;
} else if(x == -1) {
return n % 2 == 0 ? 1 : -1;
} else if(x == 0 || n >= Integer.MAX_VALUE || n <= Integer.MIN_VALUE) {
return 0;
}
int x_flag = 1;
int n_flag = n > 0 ? 1 : -1;
n = Math.abs(n);
if(x < 0 && n % 2 == 1) {
x_flag = -1;
}
x = Math.abs(x);
double sum = 1;
while(n > 1) {
if(n % 2 == 1) {
sum *= x;
}
x = x * x;
n /= 2;
}
sum = sum * x * x_flag;
if(n_flag > 0) {
return sum;
} else {
return 1 / sum;
}