Original link: leetcode-cn.com/problems/po…

Answer:

  1. Only numbers greater than 0 can be powers of 2
  2. A power of two satisfies the condition in binary: one followed by n zeros, for example8 = 00001000.
  3. If it is not a power of two, its binary has more than one 1, for example6 = 00000110.
  4. Therefore, it is only necessary to determine whether binary meets the condition of a 1 followed by n zeros. The method is as follows:
    • In order ton=8For example, the binary of 8 is00001000The binary of minus 8 is11111000.8 & -8 = 00001000Equals eight.
    • In order ton=6For example, the binary of 6 is00000110The binary of minus 6 is11111010.6 & -6 = 00000010It’s not equal to 6.
    • In order ton=7For example, the binary value of 7 is00000111The binary of minus 7 is11111001.7 & -7 = 00000001It’s not equal to 7.
    • So to determine whether n is a power of 2, you just have to determine(n & -n) === nCan. For a more detailed analysis, seeThe official answer key.
/ * * *@param {number} n
 * @return {boolean}* /
var isPowerOfTwo = function (n) {
  // Determine if n is greater than 0 and (n & -n) === n.
  return n > 0 && (n & -n) === n;
};
Copy the code