231. Power of Two
Given an integer 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 n == 2^x n==2x.
Example 1:
Input: n = 1
Output: true
Explanation: 2 0 = 1 2^0 = 1 20=1
Example 2:
Input: n = 16
Output: true
Explanation: 2 4 = 16 2^4 = 16 24=16
Example 3:
Input: n = 3
Output: false
Constraints:
- − 2 31 < = n < = 2 31 − 1 -2^{31} <= n <= 2^{31} - 1 −231<=n<=231−1
From: LeetCode
Link: 231. Power of Two
Solution:
Ideas:
- Check if n is positive: The condition if (n <= 0) ensures that negative numbers and zero return false, since powers of two are always positive.
- Bitwise check: The expression (n & (n - 1)) == 0 checks if n has exactly one bit set.
Code:
c
bool isPowerOfTwo(int n) {
if (n <= 0) {
return false;
}
return (n & (n - 1)) == 0;
}