0
help in c++
How does the code given below identifies the number to be power of two or not? #include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; if( (n & (n-1)) == 0){ cout<< "power of 2"; } else{ cout<< "not power of 2"; } return 0; }
2 Respostas
+ 6
AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bit Operation of 12 and 25
00001100 & 00011001
________
00001000 = 8 (In decimal)
Same here for odd numbers condition failing so the result will be not power of 2
If u will do n&1 u will get odd numbers
+ 6
& is the bitwise operator AND
For example:
12 & 7= (in binary 1100 and 0111)
( 0 AND 1 )-> 0
( 0 AND 1 )-> 0
( 1 AND 1 )-> 1
( 1 AND 0 )-> 0
=4
Now, regarding how it checks if n=2^k, in binary 2^k is 100...0 (k times 0)
(the same way as 10^k in decimal is 100...0)
So all zeros except for the k+1 position
2^k - 1 is 011...1 (like 099...9)
As you can see it has all ones except for the k+1 position
So if we do the bitwise AND we will get 0
And it's the only set of value with this property, any other when incremented keeps at least 1 digit fixed (again, it's easier to think it in decimal)