50. Pow(x, n) (Medium)

Description:

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

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

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

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [−231, 231 − 1]

Solutions:

Solve by built-in function

class Solution:
    def myPow(self, x: float, n: int) -> float:
        return min(max(pow(x,n),-pow(2,31)),pow(2,31)-1)

Performance:

  • Runtime: 32 ms, faster than 91.33% of Python3 online submissions for Pow(x, n).
  • Memory Usage: 13.3 MB, less than 21.10% of Python3 online submissions for Pow(x, n).

Smarter solution by exponentially decaying the power: 这里n是int,所以理论上可以比built-in的pow效率更高

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1
        
        result = 1
        
        flag = n>0
        n = abs(n)
        
        if n > 0:
            result = 1
            cache = 1
            i = 0
            while(i != n):
                if i == 0: # need to be careful to the case where the power or the variable "i" == 0
                    cache *= x
                    i = 1
                else:
                    cache *= cache
                    i *= 2
                    if i*2 > n and i < n:
                        n -= i
                        i = 0
                        result *= cache # eg. n = 7 => result = x^4 * x^2 * x^1
                        cache = 1
            result *= cache # eg. n= 12 => result = x^8 * x^4 * 1, here the "1" is the cache one line backward
            
        if flag:
            return result
        else:
            return 1/result

Performance:

  • Runtime: 28 ms, faster than 98.11% of Python3 online submissions for Pow(x, n).
  • Memory Usage: 13.2 MB, less than 43.19% of Python3 online submissions for Pow(x, n).

你可能感兴趣的:(50. Pow(x, n) (Medium))