Want a Free Job Posting?

Buy a job posting today and the second one is on us. For a limited time only. Act Now.

Interview Question

Interview Santa Clara, CA

Describe a function to check if an integer is a power of 2.


Interview Answer

5 Answers


For an integer n: If n is less than 1, return false. If the bitwise & of n and n-1 is 0, return true. Otherwise, return false.

Interview Candidate on Jan 29, 2010

Write the number in binary and count the number of ones in that.If the number os ones is only 1 then it the number is indeed a power of 2

Jo on Jul 26, 2011

first check if no is 1 then return false else write the number in binary and then check number of ones in that.if only one 1 is there then its a power of 2

Anonymous on Jul 26, 2011

I think the main idea is to use recursion function, for the integer which is larger than 0, if it is 1 return true, else return function(n-1)

Anonymous on Jun 22, 2015

See if the sum of all bits is 1. If that's the case then the number is a power of 2.

Anonymous on Sep 18, 2015

Add Answers or Comments

To comment on this, Sign In or Sign Up.