50. Pow(x,n)
Implement pow(x, n), which calculates x raised to the power n (i.e., \(x^n\)).
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/2\(^{2}\) = 1/4 = 0.25
Solution:
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1.0
if n < 0:
x = 1 / x
n = -n
result = 1
while n > 0:
if n % 2 == 1:
result *= x
x *= x
n //= 2
return result
Time Complexity:
The time complexity of this function is O(log n), where n is the exponent n. This is because the algorithm divides the exponent by 2 at each iteration of the while loop until it reaches 0, which takes log(n) iterations. Each iteration takes constant time.
Space Complexity:
The space complexity of this function is O(1) because the function only uses a constant amount of extra space to store variables regardless of the size of the input.