Skip to content

50. Pow(x, n)

https://leetcode.com/problems/powx-n/

js
/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function(x, n) {
  if (n < 0) {
    return 1 / myPow(x, -n)
  }
  if (n === 0) {
    return 1
  }
  var half = myPow(x, n / 2 >> 0)
  return n % 2 === 0 ? half * half : half * half * x
}
py
class Solution(object):

    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if n < 0:
            return 1 / self.myPow(x, -n)
        if n == 0:
            return 1
        half = self.myPow(x, n // 2)
        return half * half if n % 2 == 0 else half * half * x