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 −
Let us see the following implementation to get better understanding −
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))
[22, 25, 9]
True