Can someone explain this recursive for me?

Viewed 433

I get this code from leetcode.

class Solution(object):
    def myPow(self, x, n):
         if n == 0: 
             return 1
         if n == -1: 
             return 1 / x
         return self.myPow(x * x, n / 2) * ([1, x][n % 2])

This code is used to implement poe(x, n), which means x**n in Python.

I want to know why it can implement pow(x, n).

It looks doesn't make sense...

I understand

if n == 0: 
and
if n == -1:

But the core code:

self.myPow(x * x, n / 2) * ([1, x][n % 2])

is really hard to understand.

BTW, this code only works on Python 2.7. If you want to test on Python 3, you should change

myPow(x*x, n / 2) * ([1, x][n % 2])

to

myPow(x*x, n // 2) * ([1, x][n % 2]) 
3 Answers

The right answer might be below

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

        if n == 0: 
            return 1
        if n > 0:
            return self.myPow(x * x, int(n / 2)) * ([1, x][n % 2])
        else:
            return self.myPow(x * x, int(n / 2)) * ([1, 1/x][n % 2])
Related