Determine if Number is a Power of Three in Java
The challenge
Given an integer 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<sup>x</sup>.
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
-2<sup>31</sup> <= n <= 2<sup>31</sup> - 1
The solution in Java code
Using Math.log(n) divided by Math.log(3) we can get a double back which when rounded using Math.round will result in a 3 being returned if the input number is a power of 3.
We can then compare the power of that to the input value to return a resultant boolean.
class Solution {
public boolean isPowerOfThree(int n) {
// catch the edge case
if (n==0) return false;
// use the built in Maths utils
return n == Math.pow(3, Math.round(Math.log(n)/Math.log(3)));
}
}