0
Code in c++ to do
If I give number to it 32 it is included in the Power of 2 so the output will be True if I give 56 so output is fauls can anyone ony tell me the code
3 ответов
+ 2
zabih khan ,
we may be able to help you, but you should do a serious code attempt by yourself first.
> please post your code here, so that we can see what the issue is.
+ 2
bool isPowerOfTwo = (n & (n - 1)) == 0
Where n ∈ { 2^k | k ∈ ℤ, k ≥ 0 }
if n is likely to be less then zero, then the constraint need additional check
(n & (n - 1)) == 0 && n >= 2
0
zabih khan All powers of 2 are just repetitions of multiplying by 2.
A side result is also all powers of 2 are even numbers.
So just work backwards from those 2 conditions.
Take starting number and use while loop to delete it by 2 each time.
If number ever turns up odd, it is not a power of 2.
If you reach down to 2, it is a power of 2.