Hey there! any question in your mind? Ask It Now!.

Popular Categories





How can we use one-line C expression to test whether a number is a power of 2. [No loops allowed]

+1 vote
135 views
asked in Java Interview Question by sam007 (330 points)
recategorized by Bhartesh
This question was asked me to an interview, can you tell me the exact answer?

 

1 Answer

0 votes
answered by anonymous
n && n == (n & (~n + 1))

One's complement machines will only work with the above expression. If you're only working with two's complement machines where negation may take the same or fewer clock cycles, assuming that even matters, it can be shortened to the following:

n && n == (n & -n)

I'd create a C program iterating -64 to +64 inclusive that prints the binary values as well as decimal to see why this works.

Related Questions

Not a Member yet?

Ask to Folks Login

My Account
1060 Folks are online
69 members and 991 guest online
Your feedback is highly appreciated