DEV Community

loading...

LeetCode "Pow(x, n)"

takakd profile image Takahiro Kudo ・1 min read

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

Discussion

pic
Editor guide