LeetCode has a Medium coding Problem in Its’ Algorithm Section “Pow(x n) LeetCode”. Today We are going to solve this problem in Python. LeetCode Link of the Problem is HERE
Question
Implement pow(x, n), which calculates x
raised to the power n
(i.e., xn
).
Examples
Input: x = 2.00000, n = 10 Output: 1024.00000
Input: x = 2.10000, n = 3 Output: 9.26100
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
Solution to Pow(x n) LeetCode
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
pow = 1
if n < 0:
n = (-n)
x = 1/x
while n:
# if `n` is odd, multiply the result by `x`
if n & 1:
pow *= x
# divide `n` by 2
n = n >> 1
# multiply `x` by itself
x = x * x
# return result
return pow
Success
Runtime: 21 ms, faster than 63.45% of Python online submissions for Pow(x, n).
Memory Usage: 13.3 MB, less than 68.21% of Python online submissions for Pow(x, n).
READ MORE
Python-related posts Visit HERE
C++ related posts Visit HERE
Databases related posts Visit HERE
Data Structures related posts visit HERE
Algorithms related posts visit HERE
Data Science related posts visit HERE