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 301 views
+3 votes
1 answer 863 views
–1 vote
0 answers 176 views
0 votes
0 answers 34 views
+7 votes
2 answers 682 views
0 votes
0 answers 87 views

Not a Member yet?

Ask to Folks Login

My Account
455 Folks are online
0 members and 455 guest online
Your feedback is highly appreciated