By Aalok Kumar
Hey Developers, Here is a simple C++ program to check whether a number is Power of Two or not using Bit Manipulation.
In this program, I've implemented Bitwise AND operator and Logical AND to check whether a number is Power of Two or not.
The Boolean function power_Of_Two(int n) takes one argument and returns true or false after doing necessary operations.
Let me explain the operation, if we subtract 1 from the Power of 2 numbers then all unset bits after set bit become set, and set bit becomes unset.
Now, For a number which is the Power of Two then the expression (x&(x-1)) yields 0.
But expression (x&(x-1)) will not work when n is equal to 0, to handle this case we use the expression (x&&(!(x&(x-1))).
Below is a sample output of my program:
Enter a number: 8 YES Enter a number: 15 NO
Submitted by Aalok Kumar (Aaloks766626)
Download packets of source code on Coders Packet