leetcode_326. Power of Three

来源:互联网 发布:清除文件 linux 编辑:程序博客网 时间:2024/05/16 06:37

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;
};
0 0
原创粉丝点击