Day 16 - LeetCode 326. Power of Three

題目

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?

翻譯

判斷一個整數是否是3的次方數。
進階: 不使用迴圈,遞迴解題?

想法

跑個迴圈一直除3, 發現餘數不是0, 就代表不是3的次方

三進制 : /^10*$/.test()

int 有上限 2147483647 所以可以取最大的3次方數字

自然對數 : Math.log10()

詳細參閱

https://skyyen999.gitbooks.io/-leetcode-with-javascript/content/questions/326md.html

https://discuss.leetcode.com/topic/40418/javascript-one-liner-without-any-hard-coded-numbers-is-generalizable-beats-89-39/2

https://discuss.leetcode.com/topic/65525/java-clean-code-with-explanations-and-running-time-7-solutions

https://discuss.leetcode.com/topic/63511/java-1-line-using-logs


Code

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfThree = function(n) {

    while (n > 2) {
        if (n % 3 !== 0) {
            return false;
        }
        n = n / 3 ;
    }
    return n === 1;
};
/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfThree = function(n) {
    //把數字轉成三進位制的字串, 只要是開頭1 + 1個以上的0, ex:10 100 1000 ...就代表是三的次方
    return /^10*$/.test( n.toString(3) );
};

Run

Your input
27
1
0
2
33
6
81
24
45

Your answer
true
true
false
false
false
false
true
false
false

Expected answer
true
true
false
false
false
false
true
false
false

留言