classSolution{ publicdoublemyPow(double x, int n){ if (x == 0) { return0; } if (n == 0) { return1; } long c = Math.abs((long) n); double result = 1; while (c > 0) { if ((c & 1) == 1) { result *= x; } x *= x; c >>= 1; } return n < 0 ? 1 / result : result; } }
递归
1 2 3 4 5 6 7 8 9 10 11
publicclassSolution{ publicdoublepow(double x, int n){ if(n == 0) return1; if(n<0){ n = -n; x = 1/x; } return (n%2 == 0) ? pow(x*x, n/2) : x*pow(x*x, n/2); } }