Power of Three

Lessons Learned: While loops, logarithms

Question: Given an intern n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3^x.

A simple approach to finding out if n is a power of another number, b, is if you can continuously divide n by b with no remainder, and eventually reach 1. We can utilize a while loop to achieve this:

Another approach to solving this problem is through mathematics. If we can show that n = 3^i, we can also show that i is equal to log base 3 of n:

In this case i must be an integer. We can show this in Java by dividing by 1 and seeing whether there is no remainder.

We’re done!

Source: https://leetcode.com/problems/power-of-three/

Similar Questions: