Prepin
Log in

For a provided list of integers, return 1 if the number is a power of 2, and return 0 if it is not a power of 2.

Approach / Explanation

This question requires you to create an algorithm that determines whether each integer in a specified list is a power of 2. The list can vary in length and may contain any integer values. Your objective is to return a 1 if the number is a power of 2, and a 0 if it is not. This task involves knowledge of logarithms and bitwise operations. The essential steps to solve this question are: Comprehend the definition of a power of 2. Utilize either bitwise operations or logarithms to verify if a number is a power of 2. Iterate through the list and conduct the check for each number. Return the corresponding value as the output.

Suggested Answer

Below is a sample solution that utilizes bitwise operations: Bitwise operations can determine if a number is a power of 2. The key insight is that for a number n, if it is a power of 2, the expression n & (n - 1) will yield 0. def check_power_of_2 ( nums ) : result = [ ] for num in nums : if num != 0 and ( ( num & ( num - 1 ) ) == 0 ) : result . append ( 1 ) else : result . append ( 0 ) return result This function accepts a list of integers and checks each integer to see if it is a power of 2 by applying the bitwise 'AND' operation between the number and its predecessor. If the number is a power of two, it adds 1 to the 'result'; otherwise, it adds 0. At the end, the function returns the 'result' list.

Alternative Answer

Here is a solution example that uses logarithms: A number is considered a power of 2 if the logarithm of that number with base 2 is an integer. import math def check_power_of_2 ( nums ) : result = [ ] for num in nums : if num > 0 and math . log2 ( num ) . is_integer ( ) : result . append ( 1 ) else : result . append ( 0 ) return result Similar to the solution using bitwise operations, this function accepts a list of integers and determines whether each one is a power of 2 by utilizing the properties of logarithms. It adds a 1 to the 'result' list if the number is a power of 2; otherwise, it adds a 0. At the end, the function returns the 'result' list.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Snap

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.