0% found this document useful (0 votes)
27 views

Power of 2: How To Find If A Number Is Power of 2?

This Java program takes a numeric input from the user and determines if it is a power of 2 by using a bitwise operator. It prompts the user to enter a number, parses it as an integer, and uses the tilde operator and AND operator to check if the number has only a single bit set. It then displays a message dialog indicating whether the number is a power of 2 or not.

Uploaded by

Venice Dato
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Power of 2: How To Find If A Number Is Power of 2?

This Java program takes a numeric input from the user and determines if it is a power of 2 by using a bitwise operator. It prompts the user to enter a number, parses it as an integer, and uses the tilde operator and AND operator to check if the number has only a single bit set. It then displays a message dialog indicating whether the number is a power of 2 or not.

Uploaded by

Venice Dato
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

POWER OF 2

How to find if a number is power of 2?


AVAILABLE
INPUT

num=0, other=1

PROCESSING

REQUIRED
OUTPUT

Number is a prime or not a prime number

SOURCE CODE:
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class PowerOfTwo
{
public static void main(String args[]) throws IOException
{
String in;
in = JOptionPane.showInputDialog("Enter the number : ");
int num = Integer.parseInt(in);
int other = 1;
if(((~num) & 1) == 1)
{
JOptionPane.showMessageDialog(null, num + " is a Power of 2", "IDENTFYING
NUMBER IS A POWER OF 2",
JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, num + " is not a Power of 2", "IDENTFYING
NUMBER IS A POWER OF 2",
JOptionPane.INFORMATION_MESSAGE);
}
}
}

SCREENSHOTS

You might also like