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

+1 vote
1 answer 322 views
+3 votes
1 answer 885 views
–1 vote
0 answers 189 views
+7 votes
2 answers 731 views

Not a Member yet?

Ask to Folks Login

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