privatedoublepow(double x, int n){ if (n == 0) return1; if (n == 1) return x; double y = pow(x, n / 2); if (n % 2 == 0) { return y * y; } else { return y * y * x; } } }
循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution{ publicdoublemyPow(double x, int n){ if (x == 0) return0; long b = n; double res = 1.0; if (b < 0) { x = 1 / x; b = -b; } while (b > 0) { if ((b & 1) == 1) res *= x; x *= x; b >>= 1; } return res; } }