Monday, June 21, 2021
Home coding Write a program to find whether number is power of 2?

Write a program to find whether number is power of 2?

Given a number we have to check that number is power of 2 or not.

So what is power of 2?

power of 2 is the number which is in the form of 2^n,where n is any number.

Example:

input:4
output:true

input:12
output:false

Logic:

we have to calculate log2 of number,if it return integer value then it is power of 2.

Code-

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cout<<"enter a number"<<endl;
    cin>>n;
if(ceil(log2(n))==floor(log2(n)))
{
    cout<<"number is power of 2"<<endl;
}
else
{
    cout<<"number is not power of 2"<<endl;
}


}

Output:

enter a number:32
number is power of 2

Time complexity:0(1)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments