Power of Three
Problem
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 == 3x
.
Example 1:
Input: n = 27 Output: true
Example 2:
Input: n = 0 Output: false
Example 3:
Input: n = 9 Output: true
Constraints:
-231 <= n <= 231 - 1
Solution
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function(n) {
if (n < 1) return false;
while (n % 3 === 0) n /= 3;
return n === 1;
};
Keep dividing n
by 3
until there is a non-zero remainder.
Follow-up
Could you solve it without loops/recursion?
Solution
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function(n) {
if (n <= 0) {
return false;
}
const epsilon = 10e-12;
const val = (Math.log(n) / Math.log(3)) % 1;
return val < epsilon;
};
Using basic logarithmic rules, we can test if is an integer. Note that due to limitations of floating point arithmetics, we use an epsilon
value to determine if we're "close enough" to be consider an integer.