Pow

Implement pow(x, n).

Solution:

  1. public class Solution {
  2. public double myPow(double x, int n) {
  3. if (x == 0) return 0;
  4. if (n == 0) return 1;
  5. double pow = myPow(x, Math.abs(n) / 2);
  6. double res = pow * pow;
  7. if ((n & 1) != 0) res *= x;
  8. return n < 0 ? 1 / res : res;
  9. }
  10. }