Original link: leetcode-cn.com/problems/po…

Answer:

  1. X to the NTH power can be decomposed as x to the n over 2 squared.
  2. According to the idea of Step 1, the time complexity is O(logn) through recursive decomposition step by step.
  3. If n is negative, the problem can be converted to calculating 1 over x to the NTH power.
/ * * *@param {number} x
 * @param {number} n
 * @return {number}* /
var myPow = function (x, n) {
  // 0 and 1 to the NTH are themselves
  if (x === 1 || x === 0) {
    return x;
  }
  // The odd power of -1 is -1
  // An even power of -1 equals 1
  if (x === -1) {
    return n % 2 ? -1 : 1;
  }
  // Recursive termination condition
  // x to the 0 is 1
  if (n === 0) {
    return 1;
  }

  // If n > 0, calculate the n power normally
  if (n > 0) {
    // n to the power is equal to n over 2 squared
    // If n is odd, we need to multiply by x
    const res = myPow(x, Math.floor(n / 2));
    return n % 2 ? res * res * x : res * res;
  } else {
    // If n < 0, change the problem to 1/x^n
    return 1/ myPow(x, -n); }};Copy the code