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?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
题目要求判断n是否为3的幂,如果用loop或者recursion一层一层的被3除就可以了。但题目要求不用loop或recursion。
我用了math.pow()方法。找到整数范围内3的最大幂值,也就是3^19(3^20 超出了整数范围 2^31-1)去对n取模,判断结果是否为零。
/**
* @param {number} n* @return {boolean}
*/
var isPowerOfThree = function(n) {
var Max = Math.pow(3, 19);
if( n > 0 && Max%n === 0){
return true;
}else
return false;
};