Implement pow(x, n).
/** * A constant holding the minimum value an {@code int} can * have, -2<sup>31</sup>. */ @Native public static final int MIN_VALUE = 0x80000000; /** * A constant holding the maximum value an {@code int} can * have, 2<sup>31</sup>-1. */ @Native public static final int MAX_VALUE = 0x7fffffff;
int的表示范围是[-231, 231-1],当n为MIN_VALUE时,取反会溢出。
public double myPow(double x, int n) {
if (n == Integer.MIN_VALUE) //-INT_MIN will cause overflow
return myPow(x, n + 1) / x;
if (n < 0) return 1 / myPow(x, -n);
if (n == 0) return 1;
double halfResult = myPow(x, n >> 1);
return n % 2 == 0 ? halfResult * halfResult : halfResult * halfResult * x;
}