Skip to content

Commit db6cbde

Browse files
committed
program to find power of 2
1 parent 518d699 commit db6cbde

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

Bit Manipulation/PowerOf2.cpp

+13
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,23 @@ int powerof2(int n)
1414
else return false;
1515
}
1616

17+
int powerofTwo(int n)
18+
{
19+
if(n==1) return 0;
20+
21+
return ((n & n-1)==0) ;
22+
23+
}
24+
/*In the above method if n is a power of 2 , then n-1 will have all the bits set from lSB to the set bit of n, as every power
25+
of 2 has only 1 set bit. And when we do n & n-1 , if it is 0 then n is a power of 2
26+
*/
27+
28+
1729
int main()
1830
{
1931

2032
cout<<powerof2(1024);
33+
2134

2235
return 0;
2336
}

0 commit comments

Comments
 (0)