Program Discussion :: Bitwise Operator
15 / 15
Write an efficient program to check whether given number is power of two 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:
Jyoti Choudhary
14 May, 2017 11:18 PM
import java.util.*;
import java.lang.*;
import java.io.*;
class power_of_two
{
public static void main(String args[])
{
int num;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number : ");
num = in.nextInt();
if((num & (num-1))==0)
System.out.println(num + "number is power of two");
else
System.out.println(num+ " number is not power of two");
}
}
Language:
Varun
1 Jul, 2017 11:07 PM
<!DOCTYPE html>
<html>
<body>
<?php
function Power() {
$number=20;
$num=$number;
$flag=0;
/*check power of two*/
while($num!=1)
{
if($num%2!=0)
{
$flag=1;
break;
}
$num=$num/2;
}
if($flag==0)
echo $number." is a number that is the power of 2.";
else
echo $number." is a number that is not the power of 2.";
}
Power() ;
?>
</body>
</html>
Language:
Rakool
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:
Neha
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.io.*;
public class PowerOf2
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number: ");
int num=Integer.parseInt(br.readLine());
if(power(num))
{
System.out.println("Yes! It is a power of 2");
}
else
{
System.out.println("No! It is not a power of 2");
}
}
public static boolean power(int num)
{
if((num%2)!=0)
{
return false;
}
else
{
for(int i=0;i<=num;i++)
{
if(Math.pow(2,i)==num)
return true;
}
}
return false;
}
}