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