0

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.

3
Contributors
5
Replies
7
Views
6 Years
Discussion Span
Last Post by pyTony
0

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

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.