LeetCode Entry
231. Power of Two
Is int 32 power of 2?
231. Power of Two easy
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1075
Problem TLDR
Is int 32 power of 2? #easy #bits
Intuition
Any negative number is not power of 2 by problem description.
Approach
- there are built-in functions
Complexity
-
Time complexity: \(O(1)\),
-
Space complexity: \(O(1)\)
Code
```kotlin [-Kotlin (0ms]
// 0ms fun isPowerOfTwo(n: Int) = n > 0 && n.countOneBits() < 2
```kotlin [-0ms)]
// 0ms
fun isPowerOfTwo(n: Int) =
n > 0 && n and (n - 1) < 1
```rust [-Rust (0ms]
// 0ms pub fn is_power_of_two(n: i32) -> bool { n > 0 && n.count_ones() == 1 }
```rust [-0ms]
// 0ms
pub fn is_power_of_two(n: i32) -> bool {
n > 0 && (n as u32).is_power_of_two()
}
```c++ [-c++ (0ms]
// 0ms bool isPowerOfTwo(int n) { return n > 0 && !(n&(n-1)); }
```c++[-0ms]
// 0ms
bool isPowerOfTwo(int n) {
return n > 0 && __builtin_popcount(n) < 2;
}
```python [-python 0ms]
// 0ms def isPowerOfTwo(_, n: int) -> bool: return n > 0 and not n & (n-1)
```