Given an integer, write a function to determine if it is a power of three.
Follow up: Could you do it without using any loop / recursion?
Solution 1
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function(n) {
"use strict";
if (n === 0) {
return false;
}
while (n !== 1) {
n /= 3;
if (!Number.isInteger(n)) {
return false;
}
}
return true;
};
Solution 2
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function(n) {
"use strict";
let str = n.toString(3);
str = str.replace(/0/g, "");
return str === "1";
};