Leetcode: Power of three
Given a number
n, check if this number is a power of three, that is that it can be represented by
A straightforward solution looks as follows. Multiply by
3 until we reach
n. If we’re greater than
A mathematical more elegant solution looks as follows. Create the largest number that is less than
3^19. Then use the modulo operator to test if the number is divisible without a rest. If this is the case,
x*n == 3^19, therefore
n is a valid number.
Runtime: 80 ms, faster than 95.46% of Python3 online submissions for Power of Three. Memory Usage: 13.9 MB, less than 16.48% of Python3 online submissions for Power of Three.