
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if bitwise AND of any subset is power of two in Python
Suppose we have an array of numbers called nums. We have to check whether there exists any subset of the nums whose bitwise AND is a power of two or not.
So, if the input is like nums = [22, 25, 9], then the output will be True, as a subset {22, 9} the binary form is {10110, 1001} the AND of these two is 10000 = 16 which is power of 2.
To solve this, we will follow these steps −
- MAX := 32 considering there are 32 bits numbers at max
- Define a function solve() . This will take nums
- if size of nums is 1, then
- return true when nums[0] is power of 2, otherwise false
- total := 0
- for i in range 0 to MAX - 1, do
- total := total OR 2^i
- for i in range 0 to MAX - 1, do
- ret := total
- for j in range 0 to size of nums, do
- if nums[j] AND (2^i) is non-zero, then
- ret := ret AND nums[j]
- if nums[j] AND (2^i) is non-zero, then
- if ret is power of 2, then
- return True
- return False
Let us see the following implementation to get better understanding −
Example
MAX = 32 def is_2s_pow(v): return v and (v & (v - 1)) == 0 def solve(nums): if len(nums) == 1: return is_2s_pow(nums[0]) total = 0 for i in range(0, MAX): total = total | (1 << i) for i in range(0, MAX): ret = total for j in range(0, len(nums)): if nums[j] & (1 << i): ret = ret & nums[j] if is_2s_pow(ret): return True return False nums = [22, 25, 9] print(solve(nums))
Input
[22, 25, 9]
Output
True
- Related Articles
- Check if any permutation of N equals any power of K in Python
- Check if one list is subset of other in Python
- Check if one tuple is subset of other in Python
- Check if given number is a power of d where d is a power of 2 in Python
- Python - Check if two lists have any element in common
- Program to check a number is power of two or not in Python
- Check if any permutation of a number is divisible by 3 and is Palindromic in Python
- Check for Power of two in JavaScript
- Python Pandas – Check if any specific column of two DataFrames are equal or not
- Check if any anagram of a string is palindrome or not in Python
- Check if difference of areas of two squares is prime in Python
- Python – Check if any list element is present in Tuple
- Check if n is divisible by power of 2 without using arithmetic operators in Python
- Check if any permutation of a large number is divisible by 8 in Python
- Check if a HashSet is a subset of the specified collection in C#

Advertisements