Pow(x, n) Function Implementation

This Python code implements a function to calculate x raised to the power of n using an efficient method that leverages exponentiation by squaring. It handles both positive and negative exponents and ensures that the computation is efficient with logarithmic time complexity.
 avatar
unknown
python
10 months ago
426 B
6
Indexable
class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1.0
        
        N = n
        if N < 0:  
            x = 1 / x  
            N = -N 
        
        result = 1.0
        res = x
        
        while N > 0:
            if N % 2 == 1:  
                result *= res
            res *= res  
            N //= 2  
        
        return result
Editor is loading...
Leave a Comment