Power of Two

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write isPowerOfTwo(n): return true if the whole number n is a power of two, that is 1, 2, 4, 8, 16 and so on, and false otherwise. n can be anything from −2,147,483,648 to 2,147,483,647, so it may be 0 or negative, and neither of those is a power of two. 1 is, since it's two to the power 0. For example, isPowerOfTwo(16) is true and isPowerOfTwo(6) is false. A power of two has exactly one 1 bit in binary.

Your code must pass

  • Recognises powers of two, including 1
  • Rejects numbers that aren't powers of two
  • Rejects 0 and negative numbers
  • Handles numbers up to 2,147,483,647