Is Power of Two (Bits)

Easy~10 min

Given a positive integer n, return true if it is a power of two, or false otherwise. Solve this using bit manipulation.

A number is a power of two if it can be expressed as 2^k for some non-negative integer k. In binary, powers of two have exactly one 1-bit (e.g., 1 = 1, 2 = 10, 4 = 100, 8 = 1000).

Examples

Example 1
Input: n = 16
Output: true
Explanation: 16 = 2^4. Binary: 10000 — exactly one 1-bit.
Example 2
Input: n = 1
Output: true
Explanation: 1 = 2^0. Binary: 1 — exactly one 1-bit.
Example 3
Input: n = 6
Output: false
Explanation: 6 in binary is 110, which has two 1-bits.

Constraints

  • 1 <= n <= 2^31 - 1
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run