50. Pow(x, n)

Problem

Implement pow(x, n), which calculates x raised to the power n (i.e. xn).

 

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:

Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:

Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

 

Constraints:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • -104 <= xn <= 104

Discussion

This problem requires numerous (n) but identical operations (multiplication), which is a good set up of reduce and base algorithms. That is, we can easily reduce the data size in each iteration, and end up solve the problem by recursion. It's a type of questions like binary search.

Solution

We try to reduce the size of n by half in each iteration. For case where n is odd, we minus 1 from n and perform multiplication directly.

Moreover we have to handle the root case (n == 0) and negative n, as stated in the problem.

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1

        if n < 0:
            return self.myPow(1/x, -n)

        if n % 2 == 0:
            t = self.myPow(x, n//2)
            return t * t

        if n % 2 == 1:
            t = self.myPow(x, n//2)
            return t * t * x

Complexity Analysis

  • Time Complexity: O(log(n)), as the algorithm involves log_2(n) iterations, which is similar to binary search.
  • Space Complexity: O(log(n)), as the algorithm is recursive and involves log2(n) iterations, the root execution would hold maximum log2(n) instance.