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.
mail@pastecode.io avatar
unknown
python
23 days ago
426 B
2
Indexable
Never
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
Leave a Comment