Problem
Given an integern, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2^x.
Examples
Constraints
- -2^31 <= n <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 231 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 231 # by problem number
lcpy gen -s power_of_two # by problem name
n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2^x.
Input: n = 1
Output: true
Explanation: 2^0 = 1
Input: n = 16
Output: true
Explanation: 2^4 = 16
Input: n = 3
Output: false
class Solution:
# Time: O(1)
# Space: O(1)
def is_power_of_two(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0
| Time | Space |
|---|---|
| O(1) | O(1) |