Advertisement
smj007

Pow (x, n)

Aug 6th, 2024
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. # editorial sol
  2. class Solution:
  3.     def binaryExp(self, x: float, n: int) -> float:
  4.         # Base case, to stop recursive calls.
  5.         if n == 0:
  6.             return 1
  7.  
  8.         # Handle case where, n < 0.
  9.         if n < 0:
  10.             return 1.0 / self.binaryExp(x, -1 * n)
  11.  
  12.         # Perform Binary Exponentiation.
  13.         # If 'n' is odd we perform Binary Exponentiation on 'n - 1' and multiply result with 'x'.
  14.         if n % 2 == 1:
  15.             return x * self.binaryExp(x * x, (n - 1) // 2)
  16.         # Otherwise we calculate result by performing Binary Exponentiation on 'n'.
  17.         else:
  18.             return self.binaryExp(x * x, n // 2)
  19.  
  20.     def myPow(self, x: float, n: int) -> float:
  21.         return self.binaryExp(x, n)
  22.  
  23. # my sol
  24. class Solution:
  25.     def myPow(self, x: float, n: int) -> float:
  26.         # instead of reducing exponent n by 1
  27.         # at each recursive call we will reduce by half
  28.         if n == 0:
  29.             return 1.0
  30.         if n < 0:
  31.             return 1.0/self.myPow(x, -n)
  32.  
  33.         if n%2 == 0:
  34.             return self.myPow(x*x, n/2)
  35.         else:
  36.             return x*self.myPow(x*x, n//2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement