Java Program to Check a Given Number Is the Power of 2 Using Bitwise Operator

Java Program to Check a Given Number Is the Power of 2 Using Bitwise Operator

Java Program to Check a Given Number Is the Power of 2 Using Bitwise Operator

// Java program to check a given number is the 
// power of 2 using bitwise operator

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int num = 0;

    System.out.printf("Enter Number: ");
    num = SC.nextInt();

    if ((num & (num - 1)) == 0)
      System.out.printf("Given number is power of 2.\n");
    else
      System.out.printf("Given number is not power of 2.\n");
  }
}
Enter Number: 32
Given number is power of 2.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment