Power of Two Easy 0 attempts
LeetCode ↗

Power of Two

Easy MatrixBFSDFS LeetCode

You're given an integer n. Determine whether n is a power of two — that is, whether some non-negative integer k satisfies n = 2^k. Return true or false accordingly.

The powers of two start 1, 2, 4, 8, .... Neither zero nor any negative number qualifies here.

Input Format
Implement isPowerOfTwo(n). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 · Run Sample

Input
n = 1
Output
true

Example 2

Input
n = 16
Output
true

Example 3

Input
n = 3
Output
false
Constraints
  • -2^31 <= n <= 2^31 - 1
Test Cases (3)
Case 1
Args: [1] Expected: true
Case 2
Args: [16] Expected: true
Case 3
Args: [3] Expected: false
Topics

Bit Manipulation

javascript
function isPowerOfTwo(n) {
  return n > 0 && (n & (n - 1)) === 0;
}

Time: O(1) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript