Is n power of three – Python


Leet-Code 326. Power of Three: Question Link:

My Code:

 class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n % 3 == 0:
            if n == 3:
                return True 
            return self.isPowerOfThree(n/3)
        else: return False

I a getting the following error. Any help!
RecursionError: maximum recursion depth exceeded while getting the str of an object

>Solution :

Your function has no way of handling 0. If you step through the function, you print "0" (which is why it’s the first thing that fails after exceeding the recursion depth), then it evaluates 0 % 3 == 0. That’s True, so it goes further. 0 == 3 is False, so it returns self.isPowerOfThree(0), and you’re back where you started (infinite recursion).

Hope this helped.

Leave a ReplyCancel reply