-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

Tushar
  • 93
  • 1
  • 1
  • 7
  • 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. – kvantour Feb 10 '23 at 16:26

1 Answers1

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.

  • 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 – Tushar Feb 10 '23 at 16:27
  • Don't forget to check for negative numbers. Also `0` is not a power of three – kvantour Feb 10 '23 at 16:27
  • 1
    https://stackoverflow.com/questions/67645225/what-is-the-difference-between-and-and-in-python - `&` is "bitwise and" without short-circuiting, so `math.log10(n)` is being evaluated even if n<0 – slothrop Feb 10 '23 at 16:40