5 examples of 'check if number is power of 2' in Python

Every line of 'check if number is power of 2' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
109def is_power2(n):
110 """
111 Check if n is a power of 2
112 """
113 assert isinstance(n, int)
114 return ((n & (n-1)) == 0) and n != 0
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

24def is_a_power_of_2(x):
25 return True if x==1 else False if x%2 else is_a_power_of_2(x//2)
37def isPowerOfTwo(self, n: int) -> bool:
38 return n > 0 and not (n & (n - 1))
2def isPowerOfTwo(self, n):
3 """
4 :type n: int
5 :rtype: bool
6 """
7 return n != 0 and (n & -n) == n
37def isPowerOfFour(self, n):
38 """
39 :type num: int
40 :rtype: bool
41 """
42 if n < 1:
43 return False
44 while n > 1:
45 if n % 4 != 0:
46 return False
47 n //= 4
48 return True

Related snippets