DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

LeetCode "Pow(x, n)"

Pow(x, n)

I had amazed that everyone can write short code😨

class Solution:
    def myPow(self, x: float, n: int) -> float:

        if n == 0:
            return 1
        elif n == 1:
            return x
        elif n == -1:
            return 1/x

        n1 = int(n / 2)
        v = self.myPow(x, n1)
        if n % 2 == 0:
            v *= v
        else:
            v *= self.myPow(x, n - n1)                

        return v
Enter fullscreen mode Exit fullscreen mode

Top comments (0)