954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Power of 2

How can we calculate whether a number is a power of 2 or not in a single statement without using a loop?

All the ones that I can think of use loops or don't satisfy the condition.

for eg.

The use of XOR doesn't work as it gives incorrect input.
or maybe I'm not using it in a proper manner.

menonnik
Newbie Poster
15 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

If n is a power of 2, look at the value in binary.
Then look at the binary representation of n-1

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

ok. should i just check if it's binary representation has a single 1. but how can we implement it without a loop.

menonnik
Newbie Poster
15 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

Compare bits of n-1 with bits of n.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

thanks a ton.

menonnik
Newbie Poster
15 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

Thank Salem, he said it first.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: