Question:

Given an integer, write a function to determine if it is a power of two.

Example:

  1. Input: 1
  2. Output: true
  3. Explanation: 20 = 1
  1. Input: 16
  2. Output: true
  3. Explanation: 24 = 16
  1. Input: 218
  2. Output: false

Solution:

  1. /**
  2. * @param {number} n
  3. * @return {boolean}
  4. */
  5. var isPowerOfTwo = function(n) {
  6. let m = 1;
  7. let j = 0
  8. while( m < n ) {
  9. m = Math.pow(2,j)
  10. j++;
  11. }
  12. return m === n
  13. };

Runtime: 100 ms, faster than 30.00% of JavaScript online submissions for Power of Two.