-2

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

1
  • 1
    I would re-organize the code a bit with having your quick returns (n<=0, n==3 and n%3 !=0) immediately after your print statement. Also, you might avoid a recursive function. Commented Feb 10, 2023 at 16:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

return (n >= 0) & ((math.log10(n)/ math.log10(3) % 1) == 0) This should have worked too, but it got a math error. Any idea? @SebastianNeumann
Don't forget to check for negative numbers. Also 0 is not a power of three
stackoverflow.com/questions/67645225/… - & is "bitwise and" without short-circuiting, so math.log10(n) is being evaluated even if n<0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.