Is n power of three – Python

Question:

Leet-Code 326. Power of Three: Question Link: https://leetcode.com/problems/power-of-three/description/

My Code:

 class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        print(n)
        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

Asked By: Tushar

||

Answers:

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.

Answered By: Sebastian Neumann
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.