Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4x.
給予一個整數 n,如果他是 4 的倍數,則回傳 true。不是的話,回傳 false。 如果這裡存在一個整數 x 為 n 等於 4^x,則 n 是 4 的次方。
Example 1:
Input: n = 16 Output: true
Example 2:
Input: n = 5 Output: false
Example 3:
Input: n = 1 Output: true
Solution:
1. 先判斷 n 為負數則為 false。
2. 再判斷 n 為 1 時,回傳 true。(4^0 = 1)
3. 運用 while 迴圈,將 n > 5 的數值先行減量。
4. 再回傳 n % 4 的餘數,如為 0 則回傳 true,如為 1 則回傳 false。
Code 1:
var isPowerOfFour = function(n) { if (n <= 0) return false if (n === 1) return true while (n > 5) { n = n / 4 } return n % 4 === 0 };
FlowChart:
Example 1
Input: n = 16 while (16 > 5) {n = 16 / 4} //n = 4 return 4 % 4 === 0 //true
Example 2
Input: n = 5 return 5 % 2 !== 0 //false
Example 3
Input: n = 1 if (n === 1) return true
Code 2: Bit Manipulation
var isPowerOfFour = function(n) { return n > 0 && (n & (n - 1) === 0) && n % 3 === 1; };