Program Discussion :: Basics
75 / 279
Write a program to find the number is power of 2 or not.
Answer:
#include
#include
using namespace std;
#define bool int
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
{
/* First x in the below expression is for the case when x is 0 */
return x && (!(x&(x-1)));
}
/*Driver program to test above function*/
int main()
{
isPowerOfTwo(31)?cout
Asked In ::
Language:
Ajay
7 Jul, 2017 9:30 AM
#include<stdio.h>
#define bool int
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
{
/* First x in the below expression is for the case when x is 0 */
return x && (!(x&(x-1)));
}
/*Driver program to test above function*/
int main()
{
isPowerOfTwo(31)? printf("Yes\n"): printf("No\n");
isPowerOfTwo(17)? printf("Yes\n"): printf("No\n");
isPowerOfTwo(16)? printf("Yes\n"): printf("No\n");
isPowerOfTwo(2)? printf("Yes\n"): printf("No\n");
isPowerOfTwo(18)? printf("Yes\n"): printf("No\n");
isPowerOfTwo(1)? printf("Yes\n"): printf("No\n");
return 0;
}
Language:
Varuna Rai
7 Jul, 2017 9:30 AM
#include<stdio.h>
#include<iostream>
using namespace std;
#define bool int
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
{
/* First x in the below expression is for the case when x is 0 */
return x && (!(x&(x-1)));
}
/*Driver program to test above function*/
int main()
{
isPowerOfTwo(31)?cout<<"Yes\n": cout<<"No\n";
isPowerOfTwo(16)? cout<<"Yes\n": cout<<"No\n";
return 0;
}
Language:
Siddhartha Paul
19 Jun, 2019 2:16 PM
import java.util.Scanner;
public class PowerOfTwo
{
public static void main(String []args)
{
double x=0.0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number: ");
int n=sc.nextInt();
x=Math.log(n)/Math.log(2);
double a=Math.ceil(x);
if(x==a)
System.out.println(n+" is a power of 2");
else
System.out.println(n+" is not a power of 2");
}
}
Language:
Vasamsetti
5 Feb, 2021 10:23 AM
number=int(input("enter the number:"))
d=number/2
if d%2==0:
print("power of 2 ")
print("not a power of 2")
Language:
Vasamsetti
5 Feb, 2021 10:23 AM
number=int(input("enter the number:"))
d=number/2
if d%2==0:
print("power of 2 ")
print("not a power of 2")
Language:
Vasamsetti
5 Feb, 2021 10:23 AM
number=int(input("enter the number:"))
d=number/2
if d%2==0:
print("power of 2 ")
print("not a power of 2")
Language:
Vasamsetti
5 Feb, 2021 10:23 AM
number=int(input("enter the number:"))
d=number/2
if d%2==0:
print("power of 2 ")
print("not a power of 2")
Language:
Vasamsetti
5 Feb, 2021 10:23 AM
number=int(input("enter the number:"))
d=number/2
if d%2==0:
print("power of 2 ")
print("not a power of 2")