This can be done in one line, as you'll see elsewhere, but this solution makes it pretty clear what's going on. I was having trouble for a while because I was using
sys.float_info.epsilon for my epsilon value. But in this forum I saw someone using
1e-10, and that does the trick.
from math import log class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ if n <= 0: return False else: cube_root = log(n)/log(3) cube_root_rounded = round(cube_root) diff = abs(cube_root - cube_root_rounded) return True if diff <= 1e-10 else False