human
How do I check if a number is a power of two?
gpt
Here are a few ways to check if a number is a power of two:
1. Use bitwise and operator:
```python
def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0
```
This works by subtracting 1 from n, which clears the least significant bit. If n is a power of 2, then n & (n-1) will be 0. Otherwise, it will be non-zero.
2. Check if there is only one bit set:
```python 
def is_power_of_two(n):
    return n > 0 and bin(n).count('1') == 1
```
This converts the number to binary using bin(n) and then counts the number of 1s. If only one bit is set, then it's a power of 2.
3. Use logarithm:
```python
def is_power_of_two(n):
    return n > 0 and (math.log2(n)).is_integer() 
```
If n is a power of 2, then log2(n) will be an integer. Otherwise it will not.
4. Iteratively divide by 2:
```python
def is_power_of_two(n):
    if n <= 0:
        return False
    while n > 1: 
        if n % 2 != 0:
            return False
        n = n / 2
    return True
```
This works by repeatedly dividing by 2. If at any point n is not divisible by 2, then we know it's not a power of 2. Otherwise, we eventually reach 1, and return True.
Hope this helps! Let me know if you have any other questions.