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
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

+1 vote
1 answer 265 views
+3 votes
1 answer 768 views
–1 vote
0 answers 145 views
0 votes
0 answers 30 views
+7 votes
2 answers 618 views
0 votes
0 answers 77 views

Not a Member yet?

Ask to Folks Login

My Account
437 Folks are online
2 members and 435 guest online
Your feedback is highly appreciated