In this program we declare two integers, one for taking input and other for storing the result and giving output. We read n and if(n&(n-1))==0 and n not equal zero, then it will enter the loop.
Let us understand this n&(n-1) and integer which is power of 2 in the binary numbers it will be 1,10,100,1000,10000 which in decimal system is 0,2,4,8,16. That number subtracting it by 1 will give 0,01,011,0111,01111 which is totally opposite of numbers which are power of 2. If we take bitwise and operator for that i.e. n&(n-1) it will always give you zero for the number which are power of 2. So through this we can understand whether the number is power of 2 or not.
Once we get to know the number is power of 2 with the help of log formula ( log2 (x) = logy (x) / logy (2)) we find the log2(n) and print the result.
Our Quiz prepared by Experts Helps you identify your knowledge in Algorithms. Everyone should atleast attempt this Quiz Once.