Leetcode - Pow(x, n)

Ji Kim·2020년 11월 4일
0

Algorithm

목록 보기
26/34

Leetcode : Pow(x,n)

Description

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

Constraints

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

Example 1

Input

x = 2.00000, n = 10

Output

1024.0000

Example 2

Input

x = 2.10000, n = 3

Output

9.26100

Example 3

Input

x = 2.00000, n = -2

Output

0.25000

Approach

First categorize the cases depending on the value of n. And use recursion to minimize the value of x.

Solution (Python)

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1.0
        if n == 1:
            return x * 1.0
        if n < 0:
            return self.myPow(1/x, -n)
        
        result = self.myPow(x * x, n // 2)
        
        if n % 2 == 1:
            result = result * x
        
        return result

Result

Runtime: 32 ms
Memory Usage: 14.1 MB
Runtime Beats 48.92% of Python Submission

profile
if this then that

0개의 댓글