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.

Recommended Answers

All 5 Replies

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

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

Compare bits of n-1 with bits of n.

thanks a ton.

Thank Salem, he said it first.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.